|
| 1 | +/* Stack!! |
| 2 | +* A stack is exactly what it sounds like. An element gets added to the top of |
| 3 | +* the stack and only the element on the top may be removed. This is an example |
| 4 | +* of an array implementation of a Stack. So an element can only be added/removed |
| 5 | +* from the end of the array. |
| 6 | +*/ |
| 7 | + |
| 8 | +// Functions: push, pop, peek, view, length |
| 9 | + |
| 10 | +//Creates a stack |
| 11 | +var Stack = function () { |
| 12 | + //The top of the Stack |
| 13 | + this.top=0; |
| 14 | + //The array representation of the stack |
| 15 | + this.stack = {}; |
| 16 | + |
| 17 | + //Adds a value onto the end of the stack |
| 18 | + this.push=function(value) { |
| 19 | + this.stack[this.top]=value; |
| 20 | + this.top++; |
| 21 | + } |
| 22 | + |
| 23 | + //Removes and returns the value at the end of the stack |
| 24 | + this.pop = function(){ |
| 25 | + if(this.top === 0){ |
| 26 | + return "Stack is Empty"; |
| 27 | + } |
| 28 | + |
| 29 | + this.top--; |
| 30 | + var result = this.stack[this.top]; |
| 31 | + delete this.stack[this.top]; |
| 32 | + return result; |
| 33 | + } |
| 34 | + |
| 35 | + //Returns the size of the stack |
| 36 | + this.size = function(){ |
| 37 | + return this.top; |
| 38 | + } |
| 39 | + |
| 40 | + //Returns the value at the end of the stack |
| 41 | + this.peek = function(){ |
| 42 | + return this.stack[this.top-1]; |
| 43 | + } |
| 44 | + |
| 45 | + //To see all the elements in the stack |
| 46 | + this.view= function(){ |
| 47 | + for(var i=0;i<this.top;i++) |
| 48 | + console.log(this.stack[i]); |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +//Implementation |
| 53 | +var myStack = new Stack(); |
| 54 | + |
| 55 | +myStack.push(1); |
| 56 | +myStack.push(5); |
| 57 | +myStack.push(76); |
| 58 | +myStack.push(69); |
| 59 | +myStack.push(32); |
| 60 | +myStack.push(54); |
| 61 | +console.log(myStack.size()); |
| 62 | +console.log(myStack.peek()); |
| 63 | +console.log(myStack.pop()); |
| 64 | +console.log(myStack.peek()); |
| 65 | +console.log(myStack.pop()); |
| 66 | +console.log(myStack.peek()); |
| 67 | +myStack.push(55); |
| 68 | +console.log(myStack.peek()); |
| 69 | +myStack.view(); |
0 commit comments