前端企业面试题:企业真实案例——25

JS实现双向链表
class Node {
    constructor(value){
        this.val = value;
        this.next = null;
        this.prev = null;
    }
}

class DoubleLinkList {
    constructor(){
        //记录头和尾
        this.head = this.tail = null;
    }
    find(value) {  //查找某个元素
        var currentNode = this.head;
        while (currentNode.val != value) {
            if (currentNode.next == null) {
                return 'error';
            }
            currentNode = currentNode.next;
        }
        return currentNode;
    }
    push(value) { //像末尾添加
        var node = new Node(value);
        if(this.head == null){
            this.head = node;
            this.tail = node;
        }
        this.tail.next = node;
        node.prev = this.tail;
        this.tail = node;
    }
    pop(){ ... } //从末尾删除
    insertBefore(target, value){ ... } //插入到某个节点前面
    insertAfter(target, value) { ... } //插入到某个节点后面
    remove(value) { //删除某个节点
        var node = this.find(value);
        //如果是头结点
        if(node == this.head){
            this.head = node.next;
            this.head.prev = null;
        }
        //如果是尾节点
        if(node == this.tail){
            this.tail = this.tail.prev;
            this.tail.next = null;
        }
        //如果是中间
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
    display() { //打印所有节点
        var head = this.head
        do {
            console.log(head.element)
            head = head.next
        } while (head != null)
    }
    lastNode() { //获取最后一个节点
        return this.tail;
    }
    firstNode() { ... } //获取第一个节点
}

var list = new DoubleLinkList();
list.push("aa");
list.push("bb");
list.push("cc");
list.display();

猜你喜欢

转载自blog.csdn.net/GUDUzhongliang/article/details/108446146
今日推荐