编辑代码

class LinkedList {
    // head:对链表开头节点的引用
    // tail:对链表末尾节点的引用
    // length:链表中有多少节点
    constructor() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }

    isEmpty() {
        return this.length === 0;
    }

    printList() {
        const nodes = [];
        let current = this.head;
        while (current) {
            nodes.push(current.value);
            current = current.next;
        }
        return nodes.join(' -> ');
    }

    push(value) {
        const node = Node(value);
        if(this.head === null) {
            this.head = node;
            this.tail = node;
            this.length++;
            return node;
        }
        this.tail.next = node;
        this.tail = node;
        this.length++;
    }

    pop() {
        // 链表为空返回null
        if(this.isEmpty()) {
            return null;
        }

        // 当只有一个节点,重新设置链表
        // 记录下末尾节点内容
        const nodeToRemove = this.tail;

        // 重置链表,返回末尾节点内容
        if(this.head === this.tail) {
            this.head = null;
            this.tail = null;
            this.length--;
            return nodeToRemove;
        }

        let currentNode = this.head;
        let secondToLastNode;

        while(currentNode) {
            if(currentNode.next === this.tail) {
                secondToLastNode = currentNode;
                break;
            }
            currentNode = currentNode.next;
        }

        secondToLastNode.next = null;

        this.tail = secondToLastNode;
        this.length--;

        return nodeToRemove;
    }
}