Created
October 23, 2019 12:45
-
-
Save aire-con-gas/c0c85c0ce6a4aabbf06efdb5bb18b445 to your computer and use it in GitHub Desktop.
Reverse Linked List
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
/** | |
* Definition for singly-linked list. | |
* function ListNode(val) { | |
* this.val = val; | |
* this.next = null; | |
* } | |
*/ | |
/** | |
* @param {ListNode} head | |
* @return {ListNode} | |
*/ | |
var reverseList = function(head) { | |
const stack = []; | |
let pointer = head; | |
let newList; | |
let newHead = null; | |
while (pointer !== null) { | |
stack.push(pointer); | |
pointer = pointer.next; | |
} | |
pointer = null; | |
while(stack.length > 0) { | |
const node = stack.pop(); | |
if (newHead === null) { | |
newHead = node; | |
pointer = newHead; | |
} else { | |
pointer.next = node; | |
pointer = node; | |
pointer.next = null; | |
} | |
} | |
return newHead; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment