Final Question 13
by Jake Jernigan
HTML
Please enter a full equation (using RPN notation).
<br/> Two numbers must be entered before entering a mathematical operator.
<br/> Mathematical operators are: + - * / ^ %
<br/>
<br/>
<textarea id="expression" rows="2" cols="30">2 5 * 2 ^ 10 %</textarea>
<input type="button" id="PushStack" value="Evaluate Equation" onClick="RPN();" />
<br/>
<br/> Contents:
<p id="display"></p>
JavaScript
function Node(_content) {
this.next = null;
this.last = null;
this.content = _content;
}
function Stack() {
this.bottom = null;
this.top = null;
this.length = 0;
this.push = function(_content) {
if (this.bottom == null) {
this.bottom = new Node(_content);
this.top = this.bottom;
this.length++;
return this;
} else {
// attach to the top node
var addedNode = new Node(_content);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
this.length++;
return this;
}
}
this.pop = function() {
if (this.bottom == null) {
return null;
}
// only one Node
else if (this.bottom == this.top) {
var t = this.bottom.content;
this.bottom = null;
this.next = null;
this.last = null;
this.length = 0;
return t;
} else {
// remove bottom Node
var t = this.bottom.content;
this.bottom = this.bottom.next;
this.bottom.last = null;
this.length--;
return t;
}
}
this.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += node.content + " ";
node = node.next;
}
return str;
}
}
Stack.prototype.print = function() {
document.getElementById("display").innerHTML = this.toString();
}
function RPN() {
var stack = new Stack();
var expression = document.getElementById("expression").value;
var arr = expression.split(" ");
var val;
while (val = arr.shift()) {
if (!isNaN(val)) { // numeric
stack.push(val);
continue;
} else { // operand
if (val === "+") {
var add = parseInt(stack.pop()) + parseInt(stack.pop());
stack.push(add);
stack.print();
continue;
}
if (val === "-") {
var sub = stack.pop() - stack.pop();
stack.push(sub);
stack.print();
continue;
}
if (val === "*") {
...