İçeriğe atla
ΣDSA Patterns
Menü
Dil

Hızlı ve Yavaş İşaretçi

Rehber 4 / 6 · Yol 4 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Intersection of Two Linked Lists

Problem (restated)

Return the intersection node of two singly linked lists, or null.

Intuition

When a pointer ends, jump to the other list’s head. distances equalize at the intersection.

Approaches

Two-pointer switch heads

Tested only
Time O(m+n)Space O(1)

Idea. Advance a and b; null → switch head; stop when a == b.

Walkthrough. Shared tail of length c: both meet after a+c+b steps.

Trade-offs. Hash set of list A is simpler O(m) space.

Solution
export class ListNode {
  val: number; next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) { this.val = val; this.next = next; }
}
export function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
  if (!headA || !headB) return null;
  let a: ListNode | null = headA, b: ListNode | null = headB;
  while (a !== b) { a = a ? a.next : headB; b = b ? b.next : headA; }
  return a;
}
export class ListNode {
  val: number; next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) { this.val = val; this.next = next; }
}
export function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
  if (!headA || !headB) return null;
  let a: ListNode | null = headA, b: ListNode | null = headB;
  while (a !== b) { a = a ? a.next : headB; b = b ? b.next : headA; }
  return a;
}

Reflection