Skip to content

Commit 52823f8

Browse files
committed
Add week 7 solutions: reverse-linked-list
1 parent 94720e1 commit 52823f8

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

reverse-linked-list/gitsunmin.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* https://leetcode.com/problems/reverse-linked-list
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
7+
class ListNode {
8+
val: number
9+
next: ListNode | null
10+
constructor(val?: number, next?: ListNode | null) {
11+
this.val = (val === undefined ? 0 : val)
12+
this.next = (next === undefined ? null : next)
13+
}
14+
}
15+
16+
/** Not used in real problem */
17+
const arrayToListNode = (arr: number[]): ListNode | null => {
18+
if (arr.length === 0) return null;
19+
let head = new ListNode(arr[0]);
20+
let curr = head;
21+
for (let i = 1; i < arr.length; i++) {
22+
curr.next = new ListNode(arr[i]);
23+
curr = curr.next;
24+
}
25+
return head;
26+
}
27+
28+
/* Main function */
29+
function reverseList(head: ListNode | null): ListNode | null {
30+
let prev: ListNode | null = null;
31+
let current = head;
32+
33+
while (current !== null) {
34+
const next = current.next;
35+
current.next = prev;
36+
prev = current;
37+
current = next;
38+
}
39+
40+
return prev;
41+
};
42+
43+
/* Examples */
44+
const input1 = [1, 2, 3, 4, 5];
45+
const input2 = [1, 2];
46+
const input3 = [];
47+
48+
console.log('output1:', reverseList(arrayToListNode(input1)));
49+
console.log('output2:', reverseList(arrayToListNode(input2)));
50+
console.log('output3:', reverseList(arrayToListNode(input3)));

0 commit comments

Comments
 (0)