首页 > 解决方案 > 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"

标签: javascriptstack

解决方案


推荐阅读