3 ms·
// This solution stores the reverse order in the nodes themselves. It's hacky so I like it :) LinkedList.prototype.reverse = function () { var q; // Make
by icoder 14y ago
// This solution stores the reverse order in the nodes themselves. It's hacky so I like it :)
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 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 http://jsbin.com/ugojoq/67/edit
TIL :)
[/EDIT]
- vail130 14y agoLinear complexity FTW. Good find. A true developer wouldn't write something they didn't have to.