அல்கோரிதம்manipulation

Linked list manipulation

TT
Testlaa Team
May 14, 20261 min read

Manipulation — next rewire; order முக்கியம்.

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 — prev/cur/nxt.
  • cur.next update முன் move.
  • k-group variant.

Tags:

Linked listsPythonமாணவர்கள்