javascript - JavaScript Push Pop DLL 堆栈
问题描述
我正在尝试制作一个在推送操作员后合并自身的堆栈
https://jsfiddle.net/anthonyilie/285djwcz/37/
function restrict(input) {
var rx = /[^0-9,+,*,/,-]/;
input.value = input.value.replace(rx, "");
}
var Node = function(_content) {
this.next = null;
this.last = null;
this.content = _content;
}
var Stack = function() {
this.head = null;
this.top = null;
this.push = function(_content) {
if (this.head == null) {
this.head = new Node(_content);
this.top = this.head;
return this;
}
var addedNode = new Node(_content);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
return this;
}
this.pop = function() {
if (this.head == null) {
alert("The Stack is Empty");
return null;
}
var a = this.top;
this.top = this.top.last;
this.top.next = null;
return a;
}
this.toString = function() {
var str = "";
var node = this.head;
while (node != null) {
str += node.content + ":";
node = node.next;
}
return str;
}
}
let stack = new Stack();
function createStack() {
let input = document.getElementById("content").value;
if (input == "+") {
var a = stack.pop();
var b = stack.pop();
var answer = parseInt(`${a.content}`) + parseInt(`${b.content}`);
stack.push(answer);
} else {
stack.push(input)
}
document.getElementById('demo').innerHTML = 'Nodes ' + stack.toString();
}
Name of Node:
<br /><br />
<input type="textbox" id="content" onkeyup="restrict(this)" Value="1" />
<br /><br />
<input type="button" id="AddLink" value="PUSH" onClick="createStack();" />
<p id="demo"></p>
<p id="demo2"></p>
<br />
对于我的示例,我只是在测试“+”运算符
所以如果堆栈是 1,2,3
然后我推 +
它确实 1,5
但是如果我再次按下 + 它应该是
6
但它只是吐出一些错误,我认为这与我的指针或不应该设置为 null 的东西有关
"<a class='gotoLine' href='#85:19'>85:19</a> Uncaught TypeError: Cannot set property 'next' of null"
解决方案
推荐阅读
- reactjs - 下一个 Js 应用构建
- python - 在python中单击toast通知时如何执行功能?
- python - Matplotlib 'ValueError:子图的非法参数:(1、5)'
- python - 如何在 Rundeck 选项中使用 optiontype 作为 FILE
- javascript - Apigee Edge 插件访问正文
- php - Laravel:函数期望参数作为数组但仍然抛出错误
- c# - 表达式类,将布尔值更改为字符串比较
- flutter - 列子容器覆盖父容器的全宽
- windows - 查找是否在带有 powershell 的 Windows 10 桌面中安装了包含 20 个应用程序的文本文件中的列表
- c# - UWP 根据单击的按钮更改 SplitView.Pane 内容