A5 Hoelscher
by Tori Hoelscher
HTML
1. Please insert a number<br/>
2. Please insert another number<br/>
3. Please insert an operator (ex. *, +, -, / )
<br/><br/>
<input type='textbox' id='stack' />
<input type='button' value="Push To Stack" onclick=addStack()>
<br/> Contents Of Stack:
<p id='output'></p>
JavaScript
var Node = function(content) {
this.next = null;
this.last = null;
this.content = content;
}
var Stack = function() {
this.head = null;
this.top = null;
this.push = function(content) {
if (this.head == null) {
this.head = new Node(content);
this.top = this.head;
return this;
}
var newNode = new Node(content);
newNode.last = this.top;
this.top.next = newNode;
this.top = newNode;
return this;
}
this.pop = function() {
if (this.head == null) {
alert("The Stack is Empty");
return null;
}
if (this.head == this.top) {
this.head = 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.head;
while (node != null) {
str += node.content + " ";
node = node.next;
}
return str;
}
}
var stack = new Stack();
function addStack() {
var value = document.getElementById('stack').value;
if (value == '+') {
add();
document.getElementById('output').innerHTML = stack.toString();
}
else if (value == '-') {
subtract();
document.getElementById('output').innerHTML = stack.toString();
}
else if (value == '*') {
multiply();
document.getElementById('output').innerHTML = stack.toString();
}
else if (value == '/') {
divide();
document.getElementById('output').innerHTML = stack.toString();
}
else {
stack.push(value);
document.getElementById('output').innerHTML = stack.toString();
}
}
function add() {
var x = stack.pop();
var y = stack.pop();
var result = x + y;
stack.push(result);
}
function subtract() {
var x = stack.pop();
var y = stack.pop();
var result = x - y;
stack.push(result);
}
function multiply() {
var x = stack.pop();
var y = stack.pop();
var result = x * y;
stack.push(result);
}
function divide() {
var x =...