Reverse Linked List JavaScript

Reverse a Linked List in Javascript.
Requires Underscore.js
also here:
http://jsfiddle.net/afrascona/fuhmhqf3/

Array.prototype.getLinkedList = function () {
    var i,
        head;    
    for (i = this.length - 1; i >= 0; i -= 1) {
        head = {
            value: this[i],
            next: head
        };
    }
    return head;
};

function reverseList (head) {
    var current = head,
        tempHead,
        previous;
    while ('object' === typeof current) {
        tempHead = current.next;
        current.next = previous;
        previous = _.clone(current);
        current = _.clone(tempHead);
    }
    return previous;
}

var list = [0,1,2,3,4,5,6,7,8,9].getLinkedList();

console.dir(list);
console.dir(reverseList(list));

Leave a Reply

You must be logged in to post a comment.