Stack Calculator
Assignment 5
by Alan Harris
HTML
<label>This is an RPN calculator. Do a basic math calculation(+,-,*,/)</label><br><br>
<input type="text" id="nodeinput"><br><br>
<button onclick="addtoStack();">
Calculate
</button>
<br>
<p>
Stack content:
</p>
<div id="print"></div>
CSS
button:focus {
border: 1px solid black;
padding: 4px 4px;
}
button {
background-color: grey;
border: 1px solid black;
color: white;
padding: 4px 8px;
text-decoration: none;
margin: 4px 2px;
}
button:hover {
background-color:black;
}
JavaScript
function Node(element) {
this.content = element;
this.next = null;
this.last = null;
return this;
}
var Stack = function() {
this.head = null;
this.top = null;
this.push = function(element) {
if (this.head == null) {
this.head = new Node(element);
this.top = this.head;
return this;
}
var node_Input = new Node(element);
node_Input.last = this.top;
this.top.next = node_Input;
this.top = node_Input;
return this;
}
this.pop = function() {
if (this.head == null) {
alert("Empty Stack");
return null;
}
if (this.head == this.top) {
this.head = null;
return this.top.content;
}
var n = this.top.content;
this.top = this.top.last;
this.top.next = null;
return n;
}
this.print = function() {
var s = "";
var node = this.head;
while (node != null) {
s += node.content + " ";
node = node.next;
}
return s;
}
}
Stack.prototype.clear = function() {
this.head = null;
this.top = null;
// this.top.content = null;
this.content = null;
// this.top.next = null;
}
var rpnStack = new Stack();
function addtoStack() {
d = document.getElementById("nodeinput").value;
switch(d) {
case "+":
Add();
break;
case "-":
Subtract();
break;
case "*":
Multiply();
break;
case "/":
Divide();
break;
default: rpnStack.push(d);
}
document.getElementById("print").innerHTML = rpnStack.print();
}
function clearScreen() {
var c = "";
document.getElementById("print").innerHTML = c;
Stack.prototype.clear();
}
function Add() {
var opn2 = parseInt(rpnStack.pop());
var opn1 = parseInt(rpnStack.pop());
rpnStack.push(opn2+opn1);
}
function Subtract() {
var opn2 = parseInt(rpnStack.pop());
var opn1 = parseInt(rpnStack.pop());
rpnStack.push(opn2-opn1);
}
function Multiply() {
var opn2 = parseInt(rpnStack.pop());
var opn1 = parseInt(rpnStack.pop());
...