-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
89edeec
commit e7dc805
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// Time complexity: O(n) | ||
// Space complexity: O(n) | ||
|
||
/** | ||
* Definition for singly-linked list. | ||
* function ListNode(val, next) { | ||
* this.val = (val===undefined ? 0 : val) | ||
* this.next = (next===undefined ? null : next) | ||
* } | ||
*/ | ||
/** | ||
* @param {ListNode} head | ||
* @return {ListNode} | ||
*/ | ||
var reverseList = function (head) { | ||
const stack = []; | ||
|
||
let temp = head; | ||
while (temp) { | ||
stack.push(temp.val); | ||
temp = temp.next; | ||
} | ||
|
||
if (!stack.length) { | ||
return null; | ||
} | ||
|
||
const popped = stack.pop(); | ||
const answer = new ListNode(popped); | ||
|
||
temp = answer; | ||
while (stack.length > 0) { | ||
const popped = stack.pop(); | ||
|
||
temp.next = new ListNode(popped); | ||
temp = temp.next; | ||
} | ||
|
||
return answer; | ||
}; |