From f5880d2246f6f5765315600e7354cb5f45a53d50 Mon Sep 17 00:00:00 2001 From: Mohit Sharma Date: Thu, 3 Aug 2017 18:54:15 +0530 Subject: [PATCH] Added Stack Implementation --- Data Structures/Stack/Stack.js | 69 ++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Data Structures/Stack/Stack.js diff --git a/Data Structures/Stack/Stack.js b/Data Structures/Stack/Stack.js new file mode 100644 index 0000000000..22a79aea51 --- /dev/null +++ b/Data Structures/Stack/Stack.js @@ -0,0 +1,69 @@ +/* Stack!! +* A stack is exactly what it sounds like. An element gets added to the top of +* the stack and only the element on the top may be removed. This is an example +* of an array implementation of a Stack. So an element can only be added/removed +* from the end of the array. +*/ + +// Functions: push, pop, peek, view, length + +//Creates a stack +var Stack = function () { + //The top of the Stack + this.top=0; + //The array representation of the stack + this.stack = {}; + + //Adds a value onto the end of the stack + this.push=function(value) { + this.stack[this.top]=value; + this.top++; + } + + //Removes and returns the value at the end of the stack + this.pop = function(){ + if(this.top === 0){ + return "Stack is Empty"; + } + + this.top--; + var result = this.stack[this.top]; + delete this.stack[this.top]; + return result; + } + + //Returns the size of the stack + this.size = function(){ + return this.top; + } + + //Returns the value at the end of the stack + this.peek = function(){ + return this.stack[this.top-1]; + } + + //To see all the elements in the stack + this.view= function(){ + for(var i=0;i