初始化前无法访问'Node'

问题描述 投票:-1回答:1

我正在尝试解决以下代码中的单链列表问题:

//piece of data -val;
//reference to next node-next;

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

class SinglyLinkedList {
    constructor() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }
    push(val1) {
        var newNode = new Node(val1);
        if (!this.head) {
            this.head = newNode;
            this.tail = this.head;
        }
        else
        {
            this.tail.next=newNode;
//             this.tail=newNode
        }

    }
} 

var list2 = new SinglyLinkedList()
list2.push("hello")
list2.push(1)
// list2.push("goodbye")
 //# sourceURL=snippet:///SLL

[当我尝试运行代码时,它会返回错误:

"**Cannot access 'Node' before initialization**"

屏幕快照在这里:Screenshot

javascript
1个回答
-1
投票

只需在Node类中将node更改为Node,然后在push方法中进行更改,即可使用。我不知道自己被卡在其中的原因,但我对其进行了更改然后才起作用。

© www.soinside.com 2019 - 2024. All rights reserved.