function Stack() {
this.top = null;
this.size = 0;
}
function Node(data) {
this.data = data;
this.previous = null;
}
//create new node making it the new top node
Stack.prototype.push = function(value) {
console.log(value);
var node = new Node(value);
node.previous = this.top;
this.top = node;
this.size ++;
return this.top;
};
//retrieve top value, don't remove node
Stack.prototype.peek = function() {
if (this.size>0) {
temp = this.top;
console.log(temp.data);
return temp.data;
} else {
//The stack did not contain enough values or is EMPTY.
alert("The stack did not contain enough values or is EMPTY.");
return null;
}
};
//return the value at the top node, removing top node in the process
Stack.prototype.pop = function() {
if (this.size>0) {
temp = this.top;
this.top = this.top.previous;
this.size -= 1;
console.log(temp.data);
return temp.data;
} else {
alert("The stack did not contain enough values or is EMPTY.");
return null;
}
};
//boolean to check if stack is empty
Stack.prototype.isEmpty = function() {
return (this.size<=0);
}
//show all values top to last
Stack.prototype.print = function() {
console.log("----[ print ] ------");
var current=this.top;
while (current) {
console.log(current.data);
current = current.previous; // becomes null at top
}
console.log("----[ end of print ] ------");
}
var myStack = new Stack();
myStack.push(1);
myStack.push(2);
myStack.pop();
myStack.pop();
console.log("\n\n-----\n\n");
myStack.push(5);
myStack.push(15);
myStack.push(35);
myStack.print();
myStack.pop();
myStack.pop();
myStack.peek();
myStack.peek();
myStack.pop();
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.