Skip to content

Commit e7dc805

Browse files
committed
feat: 206. Reverse Linked List
1 parent 89edeec commit e7dc805

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

reverse-linked-list/gwbaik9717.js

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

0 commit comments

Comments
 (0)