Skip to content

Commit 16884ff

Browse files
committed
solved: 206
1 parent c20fe8d commit 16884ff

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

code/206.reverse-linked-list.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
// @leet start
10+
/**
11+
* Definition for singly-linked list.
12+
* class ListNode {
13+
* val: number
14+
* next: ListNode | null
15+
* constructor(val?: number, next?: ListNode | null) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.next = (next===undefined ? null : next)
18+
* }
19+
* }
20+
*/
21+
22+
function reverseList(head: ListNode | null): ListNode | null {
23+
const n: number[] = [];
24+
while (head) {
25+
n.push(head.val);
26+
head = head.next;
27+
}
28+
29+
/** reverse list */
30+
const nR = n.reverse();
31+
32+
/** create the start node ( empty node, so the actual node stats from next) */
33+
let node = new ListNode();
34+
const headNode = node;
35+
for (const i of nR) {
36+
node.next = new ListNode(i);
37+
node = node.next;
38+
}
39+
40+
return headNode.next;
41+
}
42+
// @leet end
43+

0 commit comments

Comments
 (0)