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) {
if(!head) return NULL;
while(head->val == val ){
head = head->next;
if(!head) return NULL;
}
ListNode* p = head;
while(p->next){
if(p->next ->val == val){
if(p->next->next == NULL)
p->next = NULL;
else
p->next = p->next->next;
}
else
p = p->next;
}
return head;
}
};
/**
* 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 = new ListNode(0);
dummy ->next = head;
ListNode* pre = dummy ;
ListNode* curr = head;
while(curr){
if(curr->val == val) pre ->next = curr->next;
else pre = pre ->next;
curr = curr->next;
}
return dummy->next;
}
};