Last active
November 10, 2016 05:25
-
-
Save tpae/678e9b3a645024c56d96d21818cd57ac to your computer and use it in GitHub Desktop.
JavaScript implementation of Stack Data Structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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