JSFiddle - React, Tailwind, and code Playground
by hesster92
HTML
<h2>
RPN Calculator
</h2>
Enter only numbers or + , - , * , /
<br><br>
<input type="textbox" id="value">
<input type="button" id="enterValue" value="Push To Stack" onClick="addToStack();">
<br> <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.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 newNode = new node(content);
newNode.last = this.top;
this.top.next = newNode;
this.top = newNode;
return this;
}
this.pop = function() {
if (this.bottom == null) {
alert("This Stack is Empty. Add a value or an operator");
return null;
}
if (this.bottom == this.top) {
this.bottom = null;
return this.top.content;
}
var x = this.top.content;
this.top = this.top.last;
this.top.next = null;
return x;
}
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 addToStack() {
var value = document.getElementById("value").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 if (value == "") {
alert("Please Enter a Number or Operator");
} else if (isNaN(value) == true) {
alert("Please enter a number");
clearDisplay();
} else {
stack.push(value);
document.getElementById("output").innerHTML = stack.toString();
clearInput();
}
}
function add() {
var value1 = stack.pop();
var value2 = stack.pop();
var result = (+value1 + +value2);
stack.push(result);
}
function...