Algorithmsmanipulation

Linked List Manipulation — Insert and Delete

TT
Testlaa Team
May 14, 20261 min read

Manipulation means rewiring next: insert after a node, delete by skipping a node, reverse—all with careful order so you do not orphan memory in thought experiments.

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 reverse(head: Node | None) -> Node | None:
    prev: Node | None = None
    cur = head
    while cur:
        nxt = cur.next
        cur.next = prev
        prev, cur = cur, nxt
    return prev

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

Key takeaways

  • Reverse uses three pointers: prev, cur, nxt.
  • Update cur.next before moving cur.
  • Same skeleton extends to pairwise reverse and k-group variants.

Tags:

Linked listsPythonStudents