[Linked List]Remove Linked List Elements

Total Accepted: 43183 Total Submissions: 160460 Difficulty: Easy

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

/**
* 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* p = head,*next=NULL,*pre=NULL;
while(p && p->val==val){
next = p->next;
delete(p);
p = next;
head = p;
}
while(p){
if(p->val == val){
pre->next = p->next;
delete(p);
p = pre->next;
}else{
pre=p;
p=p->next;
}
}
return head;
}
};
上一篇:【Android】Handler使用入门


下一篇:PHP 5.2、5.3、5.4、5.5、5.6 对比以及功能详解