Remove Element from Linked List - Node.js Data Structure

Node.js examples for Data Structure:List

Description

Remove Element from Linked List

Demo Code


function Node(value){
    this.value = value;//from   www .  jav a2  s .com
    this.next = null;
}
function SLL(){
    this.head = null;
    this.length = 0;
}
SLL.prototype.add = function(value){
    var node = new Node(value);
    var current = this.head;
    if(!current){
        this.head = node;
        this.length++;
        return node;
    }
    while(current.next){
        current = current.next;
    }
    current.next = node;
    this.length++;
    return node;
}

function removeElement(sList, val){
    var current = sList.head;
    var previous;
    if(current.value === val){
        sList.head = current.next;
        sList.length --;
    }
    while(current){
        previous = current;
        current = current.next;
        if(current.value === val){
            previous.next = current.next;
            current = previous.next
            sList.length--
        }
    }
    return sList.head;
}

var sll = new SLL();
sll.add(1)
sll.add(2)
sll.add(3)
sll.add(6)
sll.add(4)
sll.add(5)
sll.add(1)

var string = JSON.stringify(removeElement(sll,1))
console.log(string)

Related Tutorials