206. Reverse Linked List
Tags:
Easy
Skills:
Linked List
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu bạn đảo ngược một danh sách liên kết đơn (singly linked list). Nghĩa là, nếu bạn có một danh sách như sau:
1 -> 2 -> 3 -> 4 -> 5 -> null
Sau khi đảo ngược, bạn sẽ được:
5 -> 4 -> 3 -> 2 -> 1 -> null
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 reverseList(head: ListNode | null): ListNode | null {
14 let prev: ListNode | null = null;
15 let curr: ListNode | null = head;
16
17 while(curr !== null) {
18 const next: ListNode | null = curr.next;
19 curr.next = prev;
20 prev = curr;
21 curr = next;
22 }
23 return prev;
24};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 reverseList(head: ListNode | null): ListNode | null {
14 if(head === null || head.next === null) return head;
15
16 const reverse_head = reverseList(head.next);
17 head.next.next = head;
18 head.next = null
19 return reverse_head
20};