19. Remove Nth Node From End of List
June 24, 2025
04:32 AM
No headings found
Loading content...
No headings found
Problem
Bài toán yêu cầu xóa node thứ n tính từ cuối danh sách Linked List và return về head của danh sách mới
Approach
Solution
1/**
2 * Definition for singly-linked list.
3 * class ListNode {
4 * val: number
5 * next: ListNode | null
6 * constructor(val?: number, next?: ListNode | null) {
7 * this.val = (val===undefined ? 0 : val)
8 * this.next = (next===undefined ? null : next)
9 * }
10 * }
11 */
12
13function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
14 const dummy = new ListNode(0, head);
15 let fast: ListNode | null = dummy;
16 let slow: ListNode | null = dummy;
17 for(let i = 0; i < n; i++) {
18 if(fast) fast = fast.next;
19 }
20
21 while(fast && fast.next) {
22 fast = fast.next;
23 slow = slow.next;
24 }
25
26 if(slow && slow.next) {
27 slow.next = slow.next.next
28 }
29
30 return dummy.next;
31};fast lên n bướcfast lên n bước là để tạo ra khoảng cách đúng bằng n node giữa hai con trỏ fast và slow . Sau đó, khi cả hai pointer cùng di chuyển từng bước một cho đến khi fast đến cuối danh sách, thì lúc đó pointer slow sẽ đứng ngay trước node cần xóa (node thứ n từ cuối)slow.next để bỏ qua node cần xóa