Skip to content

Instantly share code, notes, and snippets.

@fxxkscript
Created March 1, 2016 08:35
Show Gist options
  • Save fxxkscript/33c6ee5d1a85a7126208 to your computer and use it in GitHub Desktop.
Save fxxkscript/33c6ee5d1a85a7126208 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) {
if (!head) {
return head;
}
var currentNode = head.next;
if (!currentNode) {
return head;
}
var previousNode = head;
var nextNode = currentNode.next;
var last;
while(currentNode) {
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
if (currentNode) {
nextNode = currentNode.next;
} else {
last = previousNode;
}
}
head.next = null;
return last;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment