JSFiddle - React, Tailwind, and code Playground
by Ron Eaglin
HTML
<input type="textbox" id='value'/>
<input type="button" id="push" value="Push to stack" onclick="push()"/>
<p id="output"></p>
JavaScript
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 addedNode = new Node(_content);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
};
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 a = this.top; // hold value for return
this.top = this.top.last;
this.top.next = null;
return a;
};
this.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += node.content + ", ";
node = node.next;
}
return str;
};
};
function clearDisplay()
{
var d="";
document.getElementById("value").value="";
};
var stack = new Stack();
var a; var b; var c;var result;
var input;
function push() //added push function
{
input=document.getElementById("value").value;
if(input ==="" || input ===" ")
{
alert ("Please enter a number");
}
stack.push(input);
document.getElementById('output').innerHTML = stack.toString();
clearDisplay();
if(input =='+')
{
var a= stack.pop();
var b= stack.pop();
alert(a);
stack.push(a+b);
document.getElementById('output').innerHTML=stack.toString();
}
};