Stacking
by vzufelt
HTML
<p>
Type operators (+, -, *, /) to perform calculation
</p>
<input type="text" id="num" />
<button onclick="createStack()" value="">Push to stack</button>
<p id='output1'></p>
<p id='output2'></p>
<p id='output3'></p>
<input type="button" value="Pop" onclick="popping" />
JavaScript
var Node = function(_content) {
this.next = null; //creating the global variables
this.last = null;
this.content = _content;
}
var Stack = function() { //creating empty stack
this.bottom = null;
this.top = null;
this.push = function(_content) { //creating a push function, adding new nodes
if (this.bottom == null) {
this.bottom = new Node(_content);
this.top = this.bottom;
return this;
}
var addedNode = new Node(_content);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
return this;
}
this.pop = function() { //function to pop
if (this.bottom == null) {
document.getElementById('output3').innerHTML = "The Stack is empty." //no nodes
return null;
}
if (this.bottom == this.top) {
this.bottom = this.top;
document.getElementById("output3").innerHTML = "This is the last node in the Stack." //only one node left
return this.top;
}
var a = this.top;
this.top = this.top.last;
this.top.next = null;
return a;
}
}
Stack.prototype.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += node.content + " ";
node = node.next;
}
return str;
}
let stack = new Stack();
function createStack() {
let input = document.getElementById("num").value;
switch(input){
case "*": //multiplication
case "/": //division
case "+": //addition
case "-": //subtraction
calculation(input);
break;
default:
stack.push(input);
}
document.getElementById('output1').innerHTML = 'Added Nodes { ' + stack.toString() + ' }';
}
function calculation() { //adding in how to calculate
let a = stack.pop();
let b = stack.pop();
let answer;
let input = document.getElementById("num").value;
switch (input) {
case "+":
answer = parseInt(`${a.content}`) + parseInt(`${b.content}`);
stack.push(answer);
break;
case "-":
answer =...