Assignment 5

Stacks

by Ron Eaglin

HTML

<body onload="createStackOn_Load()">
  <h1>Stack Computer</h1>
  Enter Stack Content: <input type="textbox" value="5" id="content" />
  <input type="button" id="button" value="Add To List!!" onclick="content_OnClick()" />
  <p>
	Welcome to the stack computer!! Here is how it works.<br> Step 1: Enter a number to insert onto the stack.<br>
	Step 2: Enter another number to insert into stack. <br> Step 3: You can continue entering numbers or if you wish
	to perform a calculation<br> simply enter either (+,-,*,/). Note!!! You must have at least 3 numbers in stack before<br>
	performing an operation.
	</p>
	<div>Stack Output Shown Belowed!!</div>
	<div id="output"></div>
</body>

JavaScript

// Node class that holds the constructor for a node and assigns it variables
class Node {
  // Global Variables

  // Constructor
  constructor(_content) {
    this.content = _content;
    this.last = null;
    this.next = null;
  }
}

// Stack class with costructor to set first and last values. Add stack methods
class Stack {
  //Global Variables

  // Constructor
  constructor() {
    this.head = null;
    this.top = null;
    this.length = 0;
  }

  // Add a Node to the stack method
  push(_content) {
    // Local Variables
    const node = new Node(_content);

    // If list is empty, add node to beginning of list
    if (this.length == 0) {
      this.head = node;
      this.tail = node;
    }
    // else if list is not empty
    else {
      this.tail.next = node;
      node.last = this.tail;
      this.tail = node;
    }
    // Update length everytime
    this.length++;
    // Return Node
    return this;
  }

  // Remove node from stack method
  pop() {
    debugger;
    // If stack is empty
    if (this.length == 0) {
      alert("The stack is empty");
      return null;
    }
    // Remove Top Node
    const removedNode = this.tail;
    // If last node in stack
    if (this.length == 1) {
      this.head = null;
      this.tail = null;
      // Otherwise do this
    } else {
      this.tail = removedNode.prev;
      this.tail.next = null;
      removedNode.last = null; // This is where throwing undefined
    }
    this.length--;
    return removedNode;
  }

  // Print stack method
  print() {
    // If empty 
    if (this.head == null) {
      return "Empty List";
    }
    // Local Variables
    var str = " ";
    var node = this.head;

    while (node != null) {
      str += node.content + "     ";
      node = node.next;
    }
    document.getElementById("output").innerHTML = str;
  }
}

// Global Variables

// Function to create stack 
function createStackOn_Load() {
  // Local Variables
  window.stackCalculator = new Stack(); // Defined list as a...