Skip to content

Commit e6fb76a

Browse files
committed
Feat: 206. Reverse Linked List
1 parent 6dd8755 commit e6fb76a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

reverse-linked-list/HC-kang.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
constructor(val?: number, next?: ListNode | null) {
5+
this.val = val === undefined ? 0 : val;
6+
this.next = next === undefined ? null : next;
7+
}
8+
}
9+
10+
/**
11+
* https://leetcode.com/problems/reverse-linked-list
12+
* T.C. O(n)
13+
* S.C. O(1)
14+
*/
15+
function reverseList(head: ListNode | null): ListNode | null {
16+
let prev: ListNode | null = null;
17+
let current: ListNode | null = head;
18+
while (current !== null) {
19+
const next = current.next;
20+
current.next = prev;
21+
prev = current;
22+
current = next;
23+
}
24+
return prev;
25+
}

0 commit comments

Comments
 (0)