无法在JavaScript变量中存储实例
我目前正在使用LinkedList在JavaScript中实现一个堆栈。但是,在实例化无法在JavaScript变量中存储实例,javascript,algorithm,Javascript,Algorithm,我目前正在使用LinkedList在JavaScript中实现一个堆栈。但是,在实例化节点类时,我遇到了一个问题。当我尝试使用变量时,让newNode=newNode(x)我得到未定义的 我不知道为什么,但我想理解。如果在repl中我运行newnode(x)我得到{val:-2,next:null}一个节点。但当我将其存储在变量中时,如果我控制台newNode,则会返回undefined /** * initialize your data structure here. */ var Mi
节点
类时,我遇到了一个问题。当我尝试使用变量时,让newNode=newNode(x)
我得到未定义的
我不知道为什么,但我想理解。如果在repl中我运行newnode(x)
我得到{val:-2,next:null}
一个节点。但当我将其存储在变量中时,如果我控制台newNode
,则会返回undefined
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.size = 0;
this.min = null;
this.first = null;
};
var Node = function(val) {
this.val = val;
this.next = null;
}
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if(this.first == null) {
this.first = new Node(x);
this.min = this.first;
this.size++;
return
}
let newNode = new Node(x);
if(newNode.val < this.min.val) {
this.min = newNode.val;
}
let oldFirst = this.first;
newNode.next = oldFirst;
this.first = newNode;
this.size++;
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if(this.first === null) {
return;
}
if(this.min === this.first) {
let current = this.first.next;
this.min = current;
while(current != null) {
if(current.val < this.min.val || this.size === 2) {
this.min = current;
}
current = current.next;
}
}
this.first = this.first.next;
this.size--;
return
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.first.val;
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.min.val;
};
// ["MinStack","push","push","push","getMin","pop","top","getMin"]
// [[],[-2],[0],[-3],[],[],[],[]]
var obj = new MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
console.log(obj.getMin())
obj.pop();
obj.top();
obj.getMin();
我缺少什么?在节点类/函数定义的括号结束后缺少分号
var Node = function(val) {
this.val = val;
this.next = null;
}
应该是
var Node = function(val) {
this.val = val;
this.next = null;
};
> x = 0
0
> let newNode = new Node(x)
undefined
> newNode
Node { val: 0, next: null }
> new Node(x)
Node { val: 0, next: null }
“Node.js本身使用repl模块为执行JavaScript提供自己的交互界面。”
根据默认情况下计算为未定义的命令,在控制台上打印未定义的命令
当您使用类似于let newNode=newNode(x)
的命令时,可以忽略未定义。但输出中的异常是
> newNode
undefined
上述情况本不应该发生
理想情况下应该是这样
> x = 0
0
> let newNode = new Node(x)
undefined
> newNode
Node { val: 0, next: null }
> new Node(x)
Node { val: 0, next: null }
下面一行有一个问题
if(newNode.val < this.min.val) {
this.min = newNode.val;
}
因此,当运行getMin
时,我访问节点的值
MinStack.prototype.getMin = function() {
return this.min.val;
};
无法复制。这个代码是在什么环境下执行的?@BenjaminEckardt我使用的是node-v14.0.0
node-inspect leetcode-stack.js
你能共享整个文件吗?这里肯定有别的事情发生了。@djfdev我刚刚用fill文件编辑了这篇文章。是的,我尝试了不同的节点版本,但我仍然不知道它是什么。如果将代码添加到提交中,则会出现超时错误
MinStack.prototype.getMin = function() {
return this.min.val;
};