LeetCode-203
Link: https://leetcode.com/problems/remove-linked-list-elements/
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
思路:先保存下原串,然后依次寻找删除即可…(链表删除方法.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* newhead = new ListNode(-1); newhead->next = head; ListNode* it = newhead; while(it->next!=NULL) { if(it->next->val == val) { it->next=it->next->next; } else { it = it->next; } } return newhead->next; } }; |
【LeetCode】203.Remove Linked List Elements