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
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
-------------------------------------------------
Using a dummy node in head to simplify the procedure!
////////////////////////////////////
//code
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//check
input
//if(head==NULL)return
head;
ListNode *p = head, *tmp = head, *dum = new ListNode(-1);
dum->next = head;
p = dum;
while (p->next != NULL){
if (p->next->val == val){
tmp = p->next;
p->next =
tmp->next;
delete tmp;
}
else p = p->next;
}
head = dum->next;
delete dum;
return head;
}
};
No comments:
Post a Comment