Skip to content

Instantly share code, notes, and snippets.

@soundstep
Created December 3, 2013 17:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soundstep/7774021 to your computer and use it in GitHub Desktop.
Save soundstep/7774021 to your computer and use it in GitHub Desktop.
Javascript linked list (reverse)
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