JSFiddle - React, Tailwind, and code Playground
by HSilvaDaytona
HTML
<input type="textbox" id="input" />
<input type="button" value="Push to Stack" id="btnStack"/>
<br />
<br /> Contents of Stack:
<div id="output">
</div>
JavaScript
var stack = new Stack();
document.getElementById("btnStack").onclick = function()
{
btnStack();
};
Node = function() {
this.next = null;
this.input = null;
}
function Stack() {
this.head = null;
this.top = null;
this.push = function(input) {
if (this.head == null) {
this.head = new Node(input);
this.top = this.head;
return this;
}
var addedNode = new Node(input);
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.node + ":";
node = node.next;
}
return str;
}
document.getElementById("output").innerHTML = str;
}
function btnStack(stack) {
var input = document.getElementById("input").value;
if (!isNaN(input)) {
stack.push(input);
} else {
var a = stack.pop();
var b = stack.pop();
if (input === "+") {
stack.push(parseInt(a) + parseInt(b));
document.getElementById('output').innerHTML= stack.toString();
} else if (input === "-") {
stack.push(parseInt(b) - parseInt(a));
document.getElementById('output').innerHTML= stack.toString();
} else if (input === "*") {
stack.push(parseInt(a) * parseInt(b));
document.getElementById('output').innerHTML= stack.toString();
} else if (input === "/") {
stack.push(parseInt(b) / parseInt(a));
document.getElementById('output').innerHTML= stack.toString();
}
}
}