Implementation of a Stack without Array - Push and Pop
Stack implementation
by chris richarde
HTML
<input type="textbox" id="value" />
<input type="button" id="stack" value="Push to Stack" onClick="Math();" />
<p id="output"></p><br>
JavaScript
var Node = function(content)
{
this.next = null;
this.last = null;
this.content = content;
}
var Stack = function() {
this.bottom = null;
this.top = null;
this.length=0;
this.push = function(content) {
// No head - create one
if (this.bottom == null) {
this.bottom = new Node(content);
this.top = this.bottom;
this.length++;
return this;
}
var addedNode = new Node(content);
addedNode.last = this.bottom;
this.bottom.last = addedNode;
this.bottom = addedNode;
this.length++;
return this;
}
this.pop = function() {
if (this.bottom == null) {
alert("The Stack is Empty");
return null;
}
// Case of one node
else if (this.bottom == this.top) {
var a = this.bottom.content;
this.bottom=null;
this.next=null;
this.last=null;
this.length=0;
return a;
}
var a = this.top.content;
this.top = this.top.last;
this.top.next = null;
this.length--;
return a;
}
this.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += node.content + ":";
node = node.next;
}
return str;
}
}
// Create a Linked List and Add Nodes
var stack = new Stack();
function Math()
{
var value = document.getElementById('value').value;
while(stack.length <= 1)
{
if (!isNaN(value) || value != "")
{
stack.push(value);
}
document.getElementById("output").innerHTML=stack.toString();
break;
}
while(isNaN(value)){
if(value== '-')
{
sub();
stack.pop();
}
if(value == '+')
{
add();
stack.pop();
}
if(value == '*')
{
mult();
stack.pop();
}
if(value== '/')
{
div();
stack.pop();
}
break;
}
}
function...