Assignment 5- Stack

by Mike Kerney

HTML

Mike Kerney <br/> Assignment #5 - The Stack<br/>
<br/><br/>
<input type="numberbox" id="number" value="0" />
<input type="button" onclick="putonstack();" value="Push to Stack" />
<br/> Please select operand:
<select id="operand">
          <option value="+">+</option>
          <option value="-">-</option>
          <option value="*">*</option>
          <option value="/">/</option>
        </select>
<br/>
<input type="button" value="Calculate" onclick="calculate();" />
<div id="output">

</div>
<div id="message">
</div>
</div>

JavaScript

function LinkedList() {

  this.head = null;
  this.tail = null;
  this.length = 0;
}

function Node(_content) {
  this.next = null;
  this.prev = null;
  this.content = _content;
}

LinkedList.prototype.pop = function() {
  var value = this.head;
  this.head = this.head.next;
  return value;
};


LinkedList.prototype.push = function(_content) {
  var node = new Node();
  node.content = _content;

  if (this.head === null) {
    this.head = node;
    this.length = 1;
    return node;
  }

  if (this.tail === null) {
    this.tail = node;
    this.tail.prev = this.head;
    this.head.next = this.tail;
    this.length++;

    return node;
  }

  this.tail.next = node;
  node.prev = this.tail;
  this.tail = node;
  return node;
}
LinkedList.prototype.print = function() {

  if (this.head === null) return "Empty List";
  var string = "";
  var node = this.head;
  while (node !== null) {
    string += node.content + " ";
    node = node.next;
  }

  return string;
};
var aList = new LinkedList();

function putonstack() {

  var c = document.getElementById("number").value;
  aList.push(c);
  document.getElementById('output').innerHTML = " ";
  document.getElementById('output').innerHTML = aList.print();
}

function calculate() {
  var operand = document.getElementById("operand").value;

  try {

    if (aList.length < 2) {
      throw "There must be at least 2 numbers to perform operation";
    } else {
      var a = parseFloat(aList.tail.prev.content);
      var b = parseFloat(aList.tail.content);
      var answer;
      
      aList.pop();
      aList.pop();
      
      if (operand == "+") {
        answer = a + b;
        aList.push(answer);
        document.getElementById('output').innerHTML = " ";
        document.getElementById('output').innerHTML = aList.print();
      } else if (operand == "-") {
        answer = a - b;
        aList.push(answer);
        document.getElementById('output').innerHTML = " ";
        document.getElementById('output').innerHTML =...