Here’s the question link on Leetcode 203. Remove Linked List Elements:-
https://leetcode.com/problems/remove-linked-list-elements/description
Contents
Brute Force – Using a New Linked List
We can create a new linked list and copy only the nodes whose values are not equal to val.
We’ll use a dummy node to make adding new nodes easier.
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy(0);
ListNode* tail = &dummy;
while(head != NULL) {
if(head->val != val) {
tail->next = new ListNode(head->val);
tail = tail->next;
}
head = head->next;
}
return dummy.next;
}
};
Optimal – In-place Removal
We don’t need to create a new linked list. We can simply change the next pointers to skip nodes that contain val.
We’ll use a dummy node again, which makes handling the head node easier.
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy(0);
dummy.next = head;
ListNode* curr = &dummy;
while(curr->next != NULL) {
if(curr->next->val == val) {
curr->next = curr->next->next;
}
else {
curr = curr->next;
}
}
return dummy.next;
}
};