Javascript Stack 链表实现



我对这个javascript链表实现感到困惑,在pop()函数中我们如何做到这一点.top.next。下一个属性在节点类中,那么我们如何用堆栈类属性 top 访问它呢?

class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
this.bottom = null;
this.length = null;
}
peek() {
return this.top;
}
push(value) {
const New_node = new Node(value);
if (this.top === null) {
this.top = New_node;
this.bottom = New_node;
} else {
New_node.next = this.top;
this.top = New_node;
}
this.length++;
return this;
}
pop() {
if (this.top === null) {
return null;
} else {
this.top = this.top.next;
}
this.length--;
return this;
}
const myStack = new Stack();
myStack.push("google");
myStack.push("facebook");
myStack.push("netflix");
myStack.pop();
console.log(myStack);

下一个属性在节点类中,那么我们如何才能使用堆栈类属性 top 访问它呢?

仅当堆栈不为空时,才可以执行此操作。所以最初,当this.topnull这是行不通的——这就是为什么在pop函数中,这种情况通过if语句以不同的方式处理的原因。

但是,如果堆栈不为空,则表示之前已经执行了push,在那里我们可以看到this.top被分配了一个节点实例:New_node,而该实例又被分配new Node(value)。因此,一旦完成此操作,this.top就是一个节点,可以使用this.top.valuethis.top.next等表达式访问其节点属性。

还要意识到valuenext是"公共"属性,因此从另一个类中访问它们没有问题。这是默认值。私有属性是JavaScript语言的后期补充,并且具有不同的名称(哈希前缀)。

最新更新