Intersection of Two Linked Lists
Problem (yeniden ifade)
İki tek yönlü bağlı listenin kesişim düğümünü döndür; yoksa null.
Sezgi
Bir işaretçi bitince diğer listenin head’ine atla. Mesafeler kesişimde eşitlenir.
Yaklaşımlar
Two-pointer head değiştirme
DoğrulanmadıFikir. a ve b’yi ilerlet; null → head değiştir; a == b olunca dur.
Yürüyüş. Uzunluğu c olan ortak kuyruk: ikisi a+c+b adım sonra buluşur.
Trade-off. A listesinin hash kümesi daha basit, O(m) bellek.
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;
}
Şablon bağlantısı
Head değiştiren two pointers; yürüyüşler kesişimde eşitlenir (döngü tespiti ailesi).
Yansıma
- İki listeyi uç uca değiştirerek eşzamanlı kuyruğa varmak. Neden uzunluk farkı kapanır?
- Kesişim yokken her iki pointer da
null’da biter — erkennullreturn yanlış pozitif midir? - Düğüm eşitliği referans mı, değer mi? (Aynı val, farklı düğüm.)