Skip to content

Commit 2a1025b

Browse files
committed
reverse-linked-list solution
1 parent cc7d2dd commit 2a1025b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

reverse-linked-list/jdy8739.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
/**
3+
* Definition for singly-linked list.
4+
* function ListNode(val, next) {
5+
* this.val = (val===undefined ? 0 : val)
6+
* this.next = (next===undefined ? null : next)
7+
* }
8+
*/
9+
/**
10+
* @param {ListNode} head
11+
* @return {ListNode}
12+
*/
13+
var reverseList = function(head) {
14+
if (head === null) {
15+
return null;
16+
}
17+
18+
if (head.next === null) {
19+
return head;
20+
}
21+
22+
const stack = [];
23+
24+
let nextNode = head;
25+
26+
while (nextNode) {
27+
stack.push(nextNode);
28+
29+
nextNode = nextNode.next;
30+
}
31+
32+
for (let i=stack.length - 1; i>=0; i--) {
33+
if (i === 0) {
34+
stack[i].next = null;
35+
} else {
36+
stack[i].next = stack[i - 1];
37+
}
38+
}
39+
40+
return stack[stack.length - 1];
41+
};
42+
43+
// 시간복잡도 O(2n)

0 commit comments

Comments
 (0)