Remove Linked List Elements

Desicription

Remove all elements from a linked list of integers that have value val.

Example:

1
2
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

Solution

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
31
32
/**
* 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) {
while(head) {
if(head->val == val) {
ListNode* tmp = head;
head = head->next;
free(tmp);
}
else
break;
}
ListNode* trav = head;
while(trav) {
while(trav->next && trav->next->val == val) {
ListNode* tmp = trav->next;
trav->next = trav->next->next;
free(tmp);
}
trav = trav->next;
}
return head;
}
};