Skip to content

Instantly share code, notes, and snippets.

@tpae
Last active November 10, 2016 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpae/678e9b3a645024c56d96d21818cd57ac to your computer and use it in GitHub Desktop.
Save tpae/678e9b3a645024c56d96d21818cd57ac to your computer and use it in GitHub Desktop.
JavaScript implementation of Stack Data Structure
// Implement a stack using LinkedLists.
// Operations:
// -> push
// -> pop
// -> peek
function StackNode(val) {
this.val = val;
this.next = null;
}
function Stack() {
this.head = null;
}
Stack.prototype.push = function(val) {
if (this.head == null) {
this.head = new StackNode(val);
} else {
var head = this.head;
this.head = new StackNode(val);
this.head.next = head;
}
};
Stack.prototype.pop = function() {
var node = this.head;
if (node !== null) {
this.head = this.head.next;
return node.val;
}
return null;
};
Stack.prototype.peek = function() {
return (this.head) ? this.head.val : null;
}
var stack = new Stack();
stack.push(5);
stack.push(11);
stack.push(10);
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.peek());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment