-
Notifications
You must be signed in to change notification settings - Fork 93
/
Remove Linked List Elements
47 lines (39 loc) · 1.19 KB
/
Remove Linked List Elements
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val)
{
// Checking if head is not the key
// If head is key then this is only tricky part of question
ListNode* temp;
// Deleter all occurance of Key if it is present as head
while(head != NULL && head->val == val){
temp = head ->next;
delete head;
head = temp;
}
// base condition
if(head == NULL) return head;
ListNode* current = head->next;
ListNode* previous = head;
while(current != NULL){
if(current->val == val){
previous->next = current->next;
delete current;
current = previous->next;
continue;
}
previous = current;
current = current->next;
}
return head;
}