Created
December 3, 2013 17:50
-
-
Save soundstep/7774021 to your computer and use it in GitHub Desktop.
Javascript linked list (reverse)
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
var Node = function(data, next) { | |
this.data = data; | |
this.next = next; | |
}; | |
var node1 = new Node('id1', | |
new Node('id2', | |
new Node('id3', | |
new Node('id4') | |
) | |
) | |
); | |
function print(node) { | |
var str = ''; | |
while (node) { | |
str += '--> ' + node.data + ' '; | |
node = node.next; | |
} | |
return str; | |
} | |
function reverse(head) { | |
if (!head || !head.next) { | |
return head; | |
} | |
var remaining = reverse(head.next); | |
var current = remaining; | |
while(current.next) { | |
current = current.next; | |
} | |
current.next = head; | |
head.next = undefined; | |
console.log(print(remaining)); | |
return remaining; | |
} | |
console.log('---------') | |
console.log('BEFORE', print(node1)); | |
reverse(node1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment