This is an implimentation of a simple calculator using a stack while not using an array,
<br/> Two numbers and at least one operator is required
<br/>
<br/>
<input type="textbox" id="value" />
<input type="button" id="AddLink" value="Push to stack" onClick="PushStack();" />
<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 addedNode = new Node(_content);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
return this;
}
this.pop = function() {
if (this.bottom == null) {
alert("The Stack is Empty");
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 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();
}
}
function addNodes() {
var x = parseInt(stack.pop());
var y = parseInt(stack.pop());
var z = x + y;
stack.push(z);
}
function subtractNodes() {
var x = parseInt(stack.pop());
var y = parseInt(stack.pop());
var z = x - y;
stack.push(z);
}
function multiplyNodes() {
var x = parseInt(stack.pop());
var y = parseInt(stack.pop());
var z...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.