Remove Linked List Elements
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
Solution: Using dummy node
There are three different situations:
- The target node might be the head
- The target node might be the tail
- The taregt node might be in the middle
In a situation like this, we can utilize the dummy head to simplify the deletion.
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode *cur = dummyHead;
while (cur && cur->next) {
if (cur->next->val == val) {
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
return dummyHead->next;
}