Middle of the Linked List
Problem (yeniden ifade)
Tek yönlü bağlı listenin head’i verildiğinde orta düğümü döndür. İki orta varsa ikincisini döndür.
Sezgi
Slow bir, fast iki adım; fast bitince slow ortadadır.
Yaklaşımlar
Fast & slow pointers
DoğrulanmadıFikir. Fast null veya fast.next null olana kadar ilerle; slow’u döndür.
Yürüyüş. 1→2→3→4→5 → slow 3’te biter; çift uzunlukta ikinci ortada biter.
Trade-off. Önce uzunluğu saymak iki geçiş; bu tek geçiş O(1) bellek.
export class ListNode {
val: number;
next: ListNode | null;
constructor(val = 0, next: ListNode | null = null) {
this.val = val;
this.next = next;
}
}
export function middleNode(head: ListNode | null): ListNode | null {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow!.next;
fast = fast.next.next;
}
return slow;
}
export class ListNode {
val: number;
next: ListNode | null;
constructor(val = 0, next: ListNode | null = null) {
this.val = val;
this.next = next;
}
}
export function middleNode(head: ListNode | null): ListNode | null {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow!.next;
fast = fast.next.next;
}
return slow;
}
Şablon bağlantısı
Fast & slow: fast bitince slow ortadadır.
Yansıma
- Çift uzunlukta ikinci ortaya düşmek için yavaş ve hızlıyı nereden başlatırsın?
- Hızlı
next.nextyokken durmak:fast && fast.nextsırası neden önemli? - Uzunluğu sayıp
n//2ilerlemek de doğru; tek geçişin kazancı nedir?