அல்கோரிதம்middle logic

Middle logic — length vs two pointer

TT
Testlaa Team
May 14, 20261 min read

Count n then walk — அல்லது two-pointer; loop condition கவனம்.

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 middle_by_len(head: Node | None) -> int | None:
    n = 0
    t = head
    while t:
        n += 1
        t = t.next
    t = head
    for _ in range(n // 2):
        t = t.next  # type: ignore
    return t.val if t else None

print(middle_by_len(from_list([1, 2, 3, 4])))

Key takeaways

  • Two-pass O(n).
  • Split problems-க்கு length.
  • ஒரே style.

Tags:

Linked listsPythonமாணவர்கள்