Last active
January 29, 2019 04:49
-
-
Save rxluz/ef9dabe16d4024d0633044821b519138 to your computer and use it in GitHub Desktop.
JS Data Structures: Stacks, see more at: https://medium.com/p/7dcea711c091
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
function Stack() { | |
let top = null | |
let size = 0 | |
class Node { | |
constructor(data) { | |
this.data = data | |
this.previous = null | |
} | |
} | |
class PublicStack { | |
push(data) { | |
const node = new Node(data) | |
node.previous = top | |
top = node | |
size++ | |
return this.top | |
} | |
pop() { | |
if (this.isEmpty()) throw new Error('This stack is empty') | |
const temp = top | |
top = top.previous | |
size-- | |
return temp | |
} | |
peek() { | |
if (this.isEmpty()) throw new Error('This stack is empty') | |
return top.data | |
} | |
isEmpty() { | |
return size === 0 | |
} | |
clear() { | |
top = null | |
} | |
size() { | |
return size | |
} | |
} | |
return new PublicStack() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment