Assignment 5 Stack
by austinmillett
October 01, 2018
HTML
<!-- Heading 1 -->
<h1> Austin Millett </h1>
<!-- Heading 2 -->
<h2> Assignment 5 - The Stack </h2>
<!-- Textbox -->
<input type = "textbox" id ="value" placeholder = "Enter Number or Operator" />
<!-- Button for Push to Stack -->
<input type = "button" value = "Push to Stack" id = "Button" onClick = "PushStack();"/>
<!-- Div for output -->
<div id = "output"> </div>
CSS
/* Design for push to stack button */
#Button {
background-color: black;
border: 2px solid;
color: white;
padding: 4px 8px;
text-align: center;
font-size: 15px;
}
JavaScript
//Linked list
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) {
if (this.bottom == null) {
this.bottom = new Node(_content);
this.top = this.bottom;
return this;
}
var addNode = new Node(_content);
addNode.last = this.top;
this.top.next = addNode;
this.top = addNode;
return this;
}
this.pop = function() {
if (this.bottom == null) {
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 for outputting operators "+, -, *, / "
function PushStack() {
var p = document.getElementById("value").value;
if (p == "+") {
addNodes();
document.getElementById('output').innerHTML = stack.toString();
} else if (p == "-") {
subtractNodes();
document.getElementById('output').innerHTML = stack.toString();
} else if (p == "*") {
multiplyNodes();
document.getElementById('output').innerHTML = stack.toString();
} else if (p == "/") {
divideNodes();
document.getElementById('output').innerHTML = stack.toString();
} else {
stack.push(p);
document.getElementById('output').innerHTML = stack.toString();
}
}
//Adding numbers
function addNodes() {
var x = parseInt(stack.pop());
var y = parseInt(stack.pop());
var z = x + y;
stack.push(z);
}
//Subtracting numbers
function subtractNodes() {
var x = parseInt(stack.pop());
var y = parseInt(stack.pop());
var z = x - y;
stack.push(z);
}
//Multiplying numbers
function...