Algorithmspointer management

Pointer Management on Linked Lists

TT
Testlaa Team
May 14, 20261 min read

Name pointers (prev, cur, nxt, l1, l2) and never reuse a stale next after reassignment—snapshot nxt = cur.next before rewiring.

Try this in Python

from __future__ import annotations
from dataclasses import dataclass


@dataclass
class Node:
    val: int
    next: Node | None = None


def to_list(head: Node | None) -> list[int]:
    out: list[int] = []
    while head:
        out.append(head.val)
        head = head.next
    return out


def from_list(vals: list[int]) -> Node | None:
    dummy = Node(0)
    cur = dummy
    for x in vals:
        cur.next = Node(x)
        cur = cur.next
    return dummy.next


def delete_val(head: Node | None, val: int) -> Node | None:
    dummy = Node(0, head)
    prev, cur = dummy, head
    while cur:
        if cur.val == val:
            prev.next = cur.next
            break
        prev, cur = cur, cur.next
    return dummy.next

h = from_list([1, 2, 3, 2])
print(to_list(delete_val(h, 2)))

Key takeaways

  • Dummy node simplifies delete-at-head.
  • Always link prev.next across the removed node.
  • Multiple deletes need a while instead of break.

Tags:

Linked listsPythonStudents