js 双向链表 插入 查找


function Node(value) {
    this.value = value;
    this.prev = null;
    this.next = null;
    return this;
}

function List() {
    this.head = new Node(null);
    this.insert = function(index, node) {
        let pNode = this.find(index);
        let nNode = pNode.next;
        pNode.next = node;
        node.next = nNode;
        node.prev = pNode;
        nNode.prev = node;
    }
    this.find = function(index) {
        let node = this.head;
        while(--index) {
            node = node.next
        }
        return node;
    }
    this.append = function(node) {
        let lastNode = this.head
        while(lastNode.next != null ) {
            lastNode = lastNode.next
        }
        node.prev = lastNode
        lastNode.next = node;
        
    }

    return this;
}

let list = new List();
let N1 = new Node(1);
let N2 = new Node(2);
let N3 = new Node(3);
let N4 = new Node(4);
let N5 = new Node(5);
let N6 = new Node(6);

list.append(N1);
list.append(N2);
list.append(N3);
list.append(N4);
list.append(N5);
list.append(N6);

list.insert(1,new Node(7))

console.log(list.find(2))

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页