JavaScript double linked list

Time:2020-2-23

JavaScript double linked list

A double linked list(doubly linked list)A linked data structure consists of a set of sequential linked records called nodes. Each node contains two fields, called links, which are references to the previous and next nodes in the node sequence

The previous link and the next link of the start node and the end node respectively point to a termination node, usually an outpost node or null, to facilitate traversal of the list. If there is only one sentinel node, the list is looped through the sentinel nodes. It can be conceptualized as two single linked tables of the same data items, but in reverse order.

class DNode {
  constructor(val) {
    this.val = val;
    this.prev = null;
    this.next = null;
  }
}

Add node

function  add(el) {
    var currNode = this.head;
    while (currNode.next != null) {
        currNode = currNode.next;
    }
    var newNode = new DNode(el);
    newNode.next = currNode.next;
    currNode.next = newNode;
}

lookup

function find(el) {
    var currNode = this.head;
    while (currNode && currNode.el != el) {
        currNode = currNode.next;
    }
    return currNode;
}

insert

function (newEl, oldEl) {
    var newNode = new DNode(newEl);
    var currNode = this.find(oldEl);
    if (currNode) {
        newNode.next = currNode.next;
        newNode.prev = currNode;
        currNode.next = newNode;
    } else {
        Throw new error ('the value corresponding to the node location specified to be inserted is not found! )
    }
}

Exhibition

// sequence
function () {
    var currNode = this.head.next;
    while (currNode) {
        console.log(currNode.el);
        currNode = currNode.next;
    }
}

// reverse order
function () {
    var currNode = this.head;
    currNode = this.findLast();
    while (currNode.prev != null) {
        console(currNode.el);
        currNode = currNode.prev;
    }
}

delete

function (el) {
    var currNode = this.find(el);
    if (currNode && currNode.next != null) {
        currNode.prev.next = currNode.next;
        currNode.next.prev = currNode.prev;
        currNode.next = null;
        currNode.previous = null;
    } else {
        Throw new error ('the corresponding node to be deleted cannot be found ');
    }
}