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
思路
把结点值不等于val的结点加入链表中
解题
c++版
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
| * 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 dummy=ListNode(-1); dummy.next=head; ListNode *pre=&dummy,*cur=head; while(cur){ if(cur->val==val){ cur=cur->next; } else{ pre->next=cur; cur=cur->next; pre=pre->next; } } pre->next=NULL; return dummy.next; } };
|
python版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Solution: def removeElements(self, head, val): dummy=ListNode(0) dummy.next=head pre=dummy cur=head while(cur): if cur.val==val: cur=cur.next else: pre.next=cur cur=cur.next pre=pre.next pre.next=None return dummy.next
|