Skip to content

Commit 643ea3e

Browse files
committed
reverse linked list solution
1 parent 54bab01 commit 643ea3e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

reverse-linked-list/hyer0705.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
13+
function reverseList(head: ListNode | null): ListNode | null {
14+
if (!head) return null;
15+
16+
let prev: ListNode | null = null;
17+
let current = head;
18+
19+
while (current) {
20+
const temp: ListNode | null = current.next;
21+
current.next = prev;
22+
prev = current;
23+
current = temp;
24+
}
25+
26+
return prev;
27+
}

0 commit comments

Comments
 (0)