Assignment 5_The Stack

Stack implementation

by ClarenceDowns

HTML

<h2>
  Add nodes to stack.
</h2>
<h2>
  Choose an operator for calculation
</h2>
<input type="text" id="num" />
<button onclick="createStack()" value="">Add to Stack</button>
<h3>
  Stack:
</h3>
<p id='output1'></p>
<p id='output2'></p>
<p id='output3'></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) {
    // No head - create one
    if (this.bottom == null) {
      this.bottom = new Node(_content);
      this.top = this.bottom;
      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.bottom == null) {
      document.getElementById('output3').innerHTML = "The Stack is empty."
      return null;
    }
    // Case of one node
    if (this.bottom == this.top) {
      this.bottom = this.top;
      document.getElementById("output3").innerHTML = "This is the last node in the Stack."
      return this.top;
    }

    // Now remove top Node
    var a = this.top; // hold value for return
    this.top = this.top.last;
    this.top.next = null;

    return a;
  }
}


Stack.prototype.toString = function() {
  var str = "";
  var node = this.bottom;

  while (node != null) {
    str += node.content + " ";
    node = node.next;
  }
  return str;
}

let stack = new Stack();
//Function called when button is clicked
function createStack() {
  let input = document.getElementById("num").value;
  
  switch(input){
  case "*":
  case "/":
  case "+":
  case "-":
  	calc(input);
    break;
    default:
    stack.push(input);
  }
  document.getElementById('output1').innerHTML = 'Added Nodes { ' + stack.toString() + ' }';
}

function calc() {
  let a = stack.pop();
  let b = stack.pop();
  let answer;
  let input = document.getElementById("num").value;

  switch (input) {
    case "+":
      answer = parseInt(`${a.content}`) + parseInt(`${b.content}`);
      stack.push(answer);
      break;
    case "-":
      answer = parseInt(`${a.content}`) -...