Created
March 1, 2016 08:35
-
-
Save fxxkscript/33c6ee5d1a85a7126208 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) { | |
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