Javascript Data Structure List Doubly Linked List 2

Description

Javascript Data Structure List Doubly Linked List 2


function DoublyLinkedListNode(data) {
    this.data = data;/*from w  w  w. j a  v  a2s. c  o m*/
    this.next = null;
    this.prev = null;
}


function DoublyLinkedList() {
    this.head = null;
    this.tail = null;
    this.size = 0;
}
DoublyLinkedList.prototype.isEmpty = function() {
    return this.size == 0;
}

DoublyLinkedList.prototype.addAtFront = function(value) {
    if (this.head === null) { //If first node
        this.head = new DoublyLinkedListNode(value);
        this.tail = this.head;
    } else {
        var temp = new DoublyLinkedListNode(value);
        temp.next = this.head;
        this.head.prev = temp;
        this.head = temp;
    }
    this.size++;
}

DoublyLinkedList.prototype.insertAtTail = function(value) {
    if (this.tail === null) { //If first node
        this.tail = new DoublyLinkedListNode(value);
        this.head = this.tail;
    } else {
        var temp = new DoublyLinkedListNode(value);
        temp.prev = this.tail;
        this.tail.next = temp;
        this.tail = temp;
    }
    this.size++;
}


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

    if (this.head !== null) {
        toReturn = this.head.data;

        if (this.tail === this.head) {
            this.head = null;
            this.tail = null;
        } else {
            this.head = this.head.next;
            this.head.prev = null;
        }
    }
    this.size--;
    return toReturn;
}


DoublyLinkedList.prototype.deleteAtTail = function() {
    var toReturn = null;

    if (this.tail !== null) {
        toReturn = this.tail.data;

        if (this.tail === this.head) {
            this.head = null;
            this.tail = null;
        } else {
            this.tail = this.tail.prev;
            this.tail.next = null;
        }
    }
    this.size--;
    return toReturn;
}

DoublyLinkedList.prototype.findStartingHead = function(value) {
    var currentHead = this.head;
    while (currentHead.next) {
        if (currentHead.data == value) {
            return true;
        }
        currentHead = currentHead.next;
    }
    return false;
}


DoublyLinkedList.prototype.findStartingTail = function(value) {
    var currentTail = this.tail;
    while (currentTail.prev) {
        if (currentTail.data == value) {
            return true;
        }
        currentTail = currentTail.prev;
    }
    return false;
}

var dll1 = new DoublyLinkedList();
dll1.addAtFront(10); // ddl1's structure: tail: 10  head: 10 
dll1.addAtFront(12); // ddl1's structure: tail: 10  head: 12
dll1.addAtFront(20); // ddl1's structure: tail: 10  head: 20
dll1.insertAtTail(30); // ddl1's structure: tail: 30  head: 20
dll1.findStartingTail(10); // true
dll1.findStartingTail(100); // false

console.log(dll1);



PreviousNext

Related