The Stack

by arosado417

HTML

<input type="text" id="value"/>
<input type="button" id="submit" value="Push to stack" onclick="submit()"/>
<div id="output">

</div>

JavaScript

var stack = new Stack();
var a;
var b; 
var input; 
var answer;

function clearDisplay() {
  //Global string d is used to hold display
  d = "";
  // The div element named output is used to display output
  document.getElementById("value").innerHTML = d;
}

function Node(_content){
this.next = null;
this.last = null;
this.content= _content;
}
function Stack(){
this.head= null;
this.top = null;
this.push = function(_content){
//No head --create a head
if(this.head == null){
this.head= new Node(_content);
this.top = this.head;
return this;
}
//if has a head add a node
var addedNode = new Node(_content);
addedNode.next = this.head;
this.head.prev= addedNode;
this.head = addedNode;
return this;
}
this.pop = function(){
if(this.head == null){
alert("The stack is empty");
return null ;
}
       
      // Now remove top Node
      var a = this.head;   // hold value for return
      this.head = this.head.next;
      if(this.head != null){
      this.head.prev = null;
      }
      
      return a.content;
    }


this.toString= function(){
var l= "";
var node= this.head;
while(node!= null){
l += node.content + " ";
node = node.next;
}
return l;
}
}

function submit(){
input = document.getElementById("value").value;
if(input == "+" || input == "-" || input == "*" || input =="/"){
a = stack.pop();
b = stack.pop();
switch(input){
case '+':
{
answer= parseInt(a) + parseInt(b);
break;
}
case"-":
{
answer= parseInt(a) - parseInt(b);
break;
}
case"*":
{
answer= parseInt(a) * parseInt(b);
break;
}
case"/":
{
answer= parseInt(a) / parseInt(b);
break;
}
}
stack.push(answer.toString());
}
else{
stack.push(input);
clearDisplay();
}
document.getElementById("output").innerHTML = stack.toString();
}