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) {
// No head - create one
if (this.bottom == null) {
this.bottom = new Node(_content);
this.top = this.bottom;
return this;
}
var addedNode = new Node(_content);
addedNode.last = this.top; // pointer to previous node
this.top.next = addedNode; // current top points to new
this.top = addedNode; // which becomes new top
return this;
}
this.pop = function() {
if (this.bottom == null) {
alert("The Stack is Empty");
return null;
}
// Case of one node
if (this.bottom == this.top) {
// Exercise for students to implement
alert("You must implement this case");
return this.top;
}
// Now remove top Node
var a = this.top; // hold value for return
this.top = this.top.last;
this.top.next = null;
return a;
}
this.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += "<br>" + node.content;
node = node.next;
}
return str;
}
}
// Create a Linked List and Add Nodes
var stack = new Stack();
var x = 0;
for (i=0;i < 10; i++) {
x = x +1;//Math.floor((Math.random() * 11) + 1);
stack.push(x);
document.getElementById('output1').innerHTML = 'Push some nodes ' + stack.toString();
}
for (i = 0; i < 5; i++) {
stack.pop();
document.getElementById('output2').innerHTML = 'Pop some objects: ' + stack.toString();
}
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.