Assignment 5

The Stack

by F Fornos

HTML

<p id='output'></p>

JavaScript

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

}
var Stack = function() {
  this.head = null;
  this.top = null;

  this.push = function(_content) {
    // No head - create one
    if (this.head == null) {
      this.head = new Node(_content);
      this.top = this.head;
      return this;
    }

    var addedNode = new Node(_content);
    addedNode.last = this.top; // pointer to previous node
    this.top.next = addedNode; // current top points to new
    this.top = addedNode; // which becomes new top
    return this;
  }


  this.pop = function() {
    if (this.head == null) {
      alert("<i>The Stack is Empty</i>");
      return null;
    }

    var a = this.top.content;
    if (this.top == this.head) {
      this.head = null;
      this.top = null;
      return a;
    } else {
      this.top = this.top.last;
      this.top.next = null;
      return a;
    }
  }

  this.toString = function() {
    var str = "";
    var node = this.head;
    if (this.head == null) {
      str = "<br/>";
    }

    while (node != null) {
      str += " <b>[</b> " + node.content + " <b>]</b> ";
      node = node.next;
    }
    return str;
  }

  this.countElements = function() {
    var countX = 0;
    var node = this.head;
    while (node != null) {
      node = node.next;
      countX = countX + 1;
    }
    return countX;
  }
}

var bCalc = '<input type="textbox" id="operatorIn" value="*" size="1"/><input type="button" value="Calculate" onClick="Calculate();" />';
var bDelete = '<input type="button" value="Delete" onClick="dlEntry();" /><br/>';
var bAddStack = '<input type="textbox" id="valueToPush" value="2" size="3"/><input type="button" value="Push to Stack" onClick="pushToStack();" />';

// inserts user selected values to stack
function pushToStack() {
  var valueToPush = document.getElementById("valueToPush").value;
  report = "";
  report += "<b>Current Status:</b> " + "<i>Inserted</i> " + valueToPush + "<br/>";
 ...