Reverse Linked List - Node.js Data Structure

Node.js examples for Data Structure:List

Description

Reverse Linked List

Demo Code


function Node(value) {
    this.next = null;//w w  w.  j a v  a 2  s.c  om
    this.value = value;
}
function SLL() {
    this.head = null;
    this.length = 0;
}

SLL.prototype.add = function (value) {
    let node = new Node(value);
    let currentNode = this.head;
    if (!currentNode) {
        this.head = node;
        this.length++;
        return node;
    }
    while (currentNode.next) {
        currentNode = currentNode.next;
    }
    currentNode.next = node;
    this.length++;
    return node;
}

function reverse(list) {
    if (!list.head) {
        return null;
    }
    if (!list.head.next) {
        return null;
    }
    var prev = list.head;
    var curr = list.head.next;
    prev.next = null;
    while (curr) {
        var temp = curr;
        curr = curr.next;
        temp.next = prev;
        prev = temp;
    }
    list = prev
    return list;
}
var sList = new SLL();
sList.add(1)
sList.add(2)
sList.add(3)
sList.add(4)
// console.log(sList)
console.log(reverse(sList))

Related Tutorials