Remove Linked List Elements

Delete every node with the given value — dummy head + walking predecessor.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
linked-list

Problem#

Remove all nodes whose val == target from a singly linked list.

Examples#

  • [1,2,6,3,4,5,6], val = 6[1,2,3,4,5]
  • [7,7,7,7], val = 7[]

Constraints#

  • 0 <= n <= 10^4.

Approach#

Dummy head + predecessor pointer. If pre->next matches, splice it out without advancing pre. Otherwise advance.

Solution#

Remove Linked List Elements
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy(0, head);
ListNode* pre = &dummy;
while (pre->next) {
if (pre->next->val == val) {
ListNode* del = pre->next;
pre->next = del->next;
delete del;
} else {
pre = pre->next;
}
}
return dummy.next;
}
};

Editorial#

Not advancing pre after a splice is the subtle bit — the new pre->next may also be a match. The dummy handles consecutive-match-at-head uniformly.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.