Node.js examples for Data Structure:Stack
Stack LIFO - Last in, first out
/*/* w w w. j a v a 2 s.c o m*/ STACK Abstract data type LIFO - Last in, first out Collection of elements with push and pop operations. Note that there is a natural order. Elements are removed in the reverse order of their addition. DO NOT use an array and the native push/pop method in your implementation. That's too easy, yeah? =P Use an object as the underlying data structure. *** Operations: myStack.push(value) => count of stack add value to collection myStack.pop() => most recent element added collection Remove item so that it is no longer in collection myStack.peek() => most recent element added collection Similiar to pop, but do not remove element from collection myStack.count() => number of elements in stack *** Additional Exercises: Modify your stack to take a max capacity and return a string if you try to add an element when there's no more room: myStack.push(value) => "Max capacity already reached. Remove element before adding a new one." Create a contains method to check if a value is in the stack: myStack.contains('findme') => true/false What's the time complexity? Create an until method to get the number of pops until you get to a certain value: stack values - (first)2-5-7-3-6-9(last) myStack.until(7) => 4 What's the time complexity? */ function Stack(capacity) { // implement me... this.storage = {}; this.size = 0; } Stack.prototype.push = function(value) { // implement me... this.size++; this.storage[this.size] = value; return this.size; }; // Time complexity: O(1) constant Stack.prototype.pop = function() { // implement me... var removedValue = this.storage[this.size]; delete(this.storage[this.size]); this.size--; return removedValue; }; // Time complexity: O(1) constant Stack.prototype.peek = function() { // implement me... return this.storage[this.size]; }; // Time complexity: O(1) constant Stack.prototype.count = function() { // implement me... return this.size; }; // Time complexity: var stack = new Stack(); console.log(stack.push('orange')); console.log(stack.push('yellow')); console.log(stack.push('pink')); console.log(stack.pop()); console.log(stack.peek()); console.log(stack.count()); console.log('stack storage:', stack.storage);