Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Created October 23, 2019 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aire-con-gas/c0c85c0ce6a4aabbf06efdb5bb18b445 to your computer and use it in GitHub Desktop.
Save aire-con-gas/c0c85c0ce6a4aabbf06efdb5bb18b445 to your computer and use it in GitHub Desktop.
Reverse Linked List
/**
* 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