Assignment 5

The Stack

by Jenni Meiklejohn

HTML

<h3><center> Assignment 5  Stacks </center></h3>
<input type="textbox" id="value" />

<input type="button" id="AddLink" value="Push to Stack" onClick="addNode();" />
<br/>
<br/> Stack:
<br/>
<div id="output">

JavaScript

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

var Stack = function() {
  this.length = 1;
  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 clearDisplay() {
  document.getElementById("value").value = "";
}

function add() {
  var n = stack.pop();
  var x = stack.pop();
  var result = +x + +n;
  stack.push(result);
  stack.length = 2;
}

function subtract() {
  var n = stack.pop();
  var x = stack.pop();
  var result = x - n;
  stack.push(result);
  stack.length = 2;
}

function multiply() {
  var n = stack.pop();
  var x = stack.pop();
  var result = x * n;
  stack.push(result);
  stack.length = 2;
}

function divide() {
  var n = stack.pop();
  var x = stack.pop();
  var result = x / n;
  stack.push(result);
  stack.length = 2;
}

function addNode() {
  var value = document.getElementById("value").value;
  if (stack.length > 2) {
    if (value == "+") {
      add();
      document.getElementById("output").innerHTML = stack.toString();
      clearDisplay();
    } else if (value == "-") {
      subtract();
      document.getElementById("output").innerHTML = stack.toString();
  ...