I am currently working on implementing an RPN calculator into a stack. The numbers push into the stack just fine, however, when trying to do operations within the stack, it seems as though there is a hiccup somewhere.
For example; when pushing 5 and 6 into the stack, the output is then 5, 6,. However upon entering + into the stack, it returns with 5, [object Object][object Object], instead of 5, 11,. How would I go about implementing future operations correctly to work within the stack and its contents?
var Node = function(_content) {
this.next = null;
this.last = null;
this.content = _content;
};
var Stack = function() {
this.top = null;
this.bottom = null;
this.push = function(_content) {
if (this.bottom == null) {
this.bottom = new Node(_content);
this.top = this.bottom;
return this;
}
var myNode = new Node(_content);
myNode.last = this.top;
this.top.next = myNode;
this.top = myNode
}
this.pop = function() {
if (this.bottom == null) {
alert("The stack is empty")
return null
}
if (this.bottom == this.top) {
this.top = this.bottom
this.top.last = null
return this.top
}
var testStack = this.top
this.top = this.top.last
this.top.next = null
return testStack
}
this.toString = function() {
var myString = ""
var node = this.bottom
while (node != null) {
myString += node.content + ", "
node = node.next;
}
return myString
}
}
function deleteScreen() {
var n = ""
document.getElementById("value").value = ""
}
var stack = new Stack()
var x
var y
var z
var result
var input
function push() {
input = document.getElementById("value").value
if (input === "" || input === " ") {
alert("Please enter a number!")
}
stack.push(input)
document.getElementById('output').innerHTML = stack.toString();
deleteScreen()
if (input == '+') {
var x = stack.pop()
var y = stack.pop()
stack.push(x + y)
document.getElementById('output').innerHTML = stack.toString();
}
};
<input style="width: 100px" type="textbox" id='value' />
<input type="button" id="assign" value="Insert Number Into Stack" onclick="push()" />
<p id="output">
</p>