அல்கோரிதம்pointer management

Pointer management

TT
Testlaa Team
May 14, 20261 min read

பெயர் pointers; rewire முன் nxt = cur.next snapshot.

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 — head delete எளிது.
  • prev.next skip.
  • பல delete — while.

Tags:

Linked listsPythonமாணவர்கள்