Algorithmslinked list

Linked List — Nodes and Next Pointers

TT
Testlaa Team
May 14, 20261 min read

A singly linked list is a chain of Node objects; each node stores a value and a reference to the next node (or None at the tail).

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

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

Key takeaways

  • Draw arrows before you code—bugs are almost always a lost next.
  • Empty list is head is None.
  • Keep dummy nodes in mind for insert-at-head patterns.

Tags:

Linked listsPythonStudents