Last active
January 10, 2018 13:54
-
-
Save mayashavin/3f2507732d457447c66da5ffe8d2c50f to your computer and use it in GitHub Desktop.
Data Structures - Stack in JS without using Array - Full Demo: https://jsfiddle.net/dpnminh/g1xy22cz/
This file contains 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
function Stack(){ | |
var stack = {}; | |
var stackSize = 0; | |
return { | |
push: function(item){ | |
stack[stackSize] = item; | |
stackSize++; | |
}, | |
pop: function(){ | |
if (this.isEmpty()){ return undefined;} | |
stackSize--; | |
var item = stack[stackSize]; | |
delete stack[stackSize]; | |
return item; | |
}, | |
peek: function(){ | |
if (this.isEmpty()){ | |
return undefined; | |
} | |
return stack[stackSize - 1]; | |
}, | |
stackEmpty: function(){ | |
while (!this.isEmpty()){ | |
this.pop(); | |
} | |
}, | |
isEmpty: function(){ | |
return stackSize === 0; | |
}, | |
size: function(){ | |
return stackSize; | |
}, | |
print: function(){ | |
var result = []; | |
for (var key in stack){ | |
result.unshift(stack[key]); | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment