The Stack

Assignment 5

by austinmillett

HTML

This is an implimentation of a simple calculator using a stack while not using an array,
<br/> Two numbers and at least one operator is required
<br/>
<br/>
<input type="textbox" id="value" />
<input type="button" id="AddLink" value="Push to stack" onClick="PushStack();" />
<br/>
<br/> Contents of Stack:
<p id='output'></p>

JavaScript

var Node = function(_content) {
  this.next = null;
  this.last = null;
  this.content = _content;

}

var Stack = function() {
  this.bottom = null;
  this.top = 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;
    return this;
  }

  this.pop = function() {
    if (this.bottom == null) {
      alert("The Stack is Empty");
      return null;
    }
    if (this.bottom == this.top) {
      this.bottom = null;
      return this.top.content;
    }
    var a = this.top.content;
    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;
  }
}

var stack = new Stack();


function PushStack() {
  var p = document.getElementById("value").value;
  if (p == "+") {
    addNodes();
    document.getElementById('output').innerHTML = stack.toString();
  } else if (p == "-") {
    subtractNodes();
    document.getElementById('output').innerHTML = stack.toString();
  } else if (p == "*") {
    multiplyNodes();
    document.getElementById('output').innerHTML = stack.toString();
  } else if (p == "/") {
    divideNodes();
    document.getElementById('output').innerHTML = stack.toString();
  } else {
    stack.push(p);
    document.getElementById('output').innerHTML = stack.toString();
  }
}

function addNodes() {
  var x = parseInt(stack.pop());
  var y = parseInt(stack.pop());
  var z = x + y;
  stack.push(z);
}

function subtractNodes() {
  var x = parseInt(stack.pop());
  var y = parseInt(stack.pop());
  var z = x - y;
  stack.push(z);
}

function multiplyNodes() {
  var x = parseInt(stack.pop());
  var y = parseInt(stack.pop());
  var z...