Losing head/tail while rewiring
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Build confidence with an intuition-first walkthrough focused on linked list fundamentals.
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1 Output: []
Example 3:
Input: head = [7,7,7,7], val = 7 Output: []
Constraints:
[0, 104].1 <= Node.val <= 500 <= val <= 50Problem summary: Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Linked List
[1,2,6,3,4,5,6] 6
[] 1
[7,7,7,7] 7
remove-element)delete-node-in-a-linked-list)delete-the-middle-node-of-a-linked-list)delete-nodes-from-linked-list-present-in-array)convert-doubly-linked-list-to-array-i)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #203: Remove Linked List Elements
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
while (pre.next != null) {
if (pre.next.val != val)
pre = pre.next;
else
pre.next = pre.next.next;
}
return dummy.next;
}
}
// Accepted solution for LeetCode #203: Remove Linked List Elements
func removeElements(head *ListNode, val int) *ListNode {
dummy := new(ListNode)
dummy.Next = head
p := dummy
for p.Next != nil {
if p.Next.Val == val {
p.Next = p.Next.Next
} else {
p = p.Next
}
}
return dummy.Next
}
# Accepted solution for LeetCode #203: Remove Linked List Elements
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy = ListNode(-1, head)
pre = dummy
while pre.next:
if pre.next.val != val:
pre = pre.next
else:
pre.next = pre.next.next
return dummy.next
// Accepted solution for LeetCode #203: Remove Linked List Elements
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
let mut dummy = Box::new(ListNode { val: 0, next: head });
let mut cur = &mut dummy;
while let Some(mut node) = cur.next.take() {
if node.val == val {
cur.next = node.next.take();
} else {
cur.next = Some(node);
cur = cur.next.as_mut().unwrap();
}
}
dummy.next.take()
}
}
// Accepted solution for LeetCode #203: Remove Linked List Elements
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function removeElements(head: ListNode | null, val: number): ListNode | null {
const dummy: ListNode = new ListNode(0, head);
let cur: ListNode = dummy;
while (cur.next != null) {
if (cur.next.val === val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return dummy.next;
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.