அல்கோரிதம்simulation

Linked list simulation

TT
Testlaa Team
May 14, 20261 min read

Process simulate — pointer நகர்த்தல்; array shift அல்ல.

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 simulate_k_steps(head: Node | None, k: int) -> list[int]:
    """Walk k edges, recording visited values (educational)."""
    out: list[int] = []
    cur = head
    while cur is not None and k > 0:
        out.append(cur.val)
        cur = cur.next
        k -= 1
    return out

h = from_list([1, 2, 3, 4, 5])
print(simulate_k_steps(h, 8))

Key takeaways

  • k steps — state machine.
  • k > length — end; ring buffer வேறு.
  • Merge lists — same discipline.

Tags:

Linked listsPythonமாணவர்கள்