Javascript Data Structure Singly Linked List Delete Duplicates

Description

Javascript Data Structure Singly Linked List Delete Duplicates

function SinglyLinkedListNode(data) {
    this.data = data;/* ww  w .j  a v  a  2  s  . co  m*/
    this.next = null;
}

function SinglyLinkedList() {
    this.head = null;
    this.size = 0;
}

SinglyLinkedList.prototype.isEmpty = function() {
    return this.size == 0;
}

SinglyLinkedList.prototype.insert = function(value) {
    if (this.head === null) { //If first node
        this.head = new SinglyLinkedListNode(value);
    } else {
        var temp = this.head;
        this.head = new SinglyLinkedListNode(value);
        this.head.next = temp;
    }
    this.size++;
}
SinglyLinkedList.prototype.remove = function(value) {
    var currentHead = this.head;
    if (currentHead.data == value) {
        // just shift the head over. Head is now this new value
        this.head = currentHead.next;
        this.size--;
    } else {
        var prev = currentHead;
        while (currentHead.next) {
            if (currentHead.data == value) {
                // remove by skipping
                prev.next = currentHead.next;
                prev = currentHead;
                currentHead = currentHead.next;
                break; // break out of the loop
            }
            prev = currentHead;
            currentHead = currentHead.next;
        }
        //if wasn't found in the middle or head, must be tail
        if (currentHead.data == value) {
            prev.next = null;
        }
        this.size--;
    }
}

SinglyLinkedList.prototype.deleteAtHead = function() {
    var toReturn = null;

    if (this.head !== null) {
      toReturn = this.head.data;
      this.head = this.head.next;
      this.size--;    
    }
    return toReturn;
}


//delete duplicates in unsorted linkedlist
function deleteDuplicateInUnsortedSll(sll1) {
    var track = [];

    var temp = sll1.head;
    var prev = null;
    while (temp) {
        if (track.indexOf(temp.data) >= 0) {
            prev.next = temp.next;
            sll1.size--;
        } else {
            track.push(temp.data);
            prev = temp;
        }
        temp = temp.next;
    }
    console.log(temp);
}


sll1 = new SinglyLinkedList();
sll1.insert(1); 
sll1.insert(1);
sll1.insert(1); 
sll1.insert(1); 
sll1.insert(1); 
sll1.insert(20); 
console.log(sll1);
deleteDuplicateInUnsortedSll(sll1);
console.log(sll1);



PreviousNext

Related