JavaScript developer, can you reverse a linked list?
blog.bolshchikov.net
blog.bolshchikov.net
LinkedList.prototype.reverse = function () { var q;
// Make doubly linked
for (q = this.head; q; q = q.next ) {
if ( q.next ) q.next.prev = q; else this.head = q;
}
// Reverse
for (q = this.head; q; q = q.prev ) {
q.next = q.prev;
}
// Better clean up
for (q = this.head; q; q = q.next ) {
q.prev = undefined;
}
};http://jsbin.com/ugojoq/43/edit
[EDIT]
Ah, I didn't know, but it possible to reverse a singly linked list without remembering the entire list:
var p = this.head, q, r;
while ( p ) {
r = q;
q = p;
p = p.next;
q.next = r;
}
this.head = q;
(blatantly based on an answer found on StackOverflow).http://jsbin.com/ugojoq/67/edit
TIL :) [/EDIT]
http://jsbin.com/ugojoq/267/edit
LinkedList.prototype.reverse = function () {
var start = this.head;
var prev = this.head;
var curr = prev.next;
prev.next = null;
while(curr !== null) {
var next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
this.head = prev;
}; LinkedList.prototype.reverse = function () {
var tail = function(prev, current){
if (current.next) {
tail(current, current.next);
} else {
this.head = current;
}
current.next = prev;
}.bind(this);
tail(null, this.head);
}; LinkedList.prototype.reverse = function () {
var rev = function(e,tail) {
if (!e) {
return tail;
} else {
var next = e.next;
e.next = tail;
return rev(next, e);
}
};
this.head = rev(this.head, null);
}; LinkedList.prototype.reverse = function () {
var next, head = null;
while (this.head !== null) {
next = this.head.next;
this.head.next = head;
head = this.head;
this.head = next;
}
this.head = head;
};