Last active
July 21, 2019 13:44
-
-
Save rshivkumar95/5f57d38f2d196692a0aab8c3fabff5d8 to your computer and use it in GitHub Desktop.
Stack Implementation using ES6
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
class Stack { | |
constructor() { | |
this.items = []; | |
} | |
push(element) { | |
this.items.push(element); | |
} | |
pop() { | |
if(this.items.length === 0) { | |
return 'Error: Underflow' | |
} | |
return this.items.pop(); | |
} | |
peek() { | |
if(this.isEmpty()) { | |
return 'Error: Empty' | |
} | |
return this.items[this.items.length - 1]; | |
} | |
printStack() { | |
if(this.isEmpty()) { | |
return 'Error: Empty' | |
} | |
let i = this.items.length; | |
while(i > 0) { | |
console.log(this.items[--i]); | |
} | |
} | |
isEmpty(){ | |
return this.items.length === 0; | |
} | |
} | |
const stack = new Stack(); | |
console.log('POPED :: ' + stack.pop()); | |
stack.push(1); | |
stack.push(2); | |
stack.push(3); | |
console.log('PEEK :: '+ stack.peek()); | |
stack.push(4); | |
stack.push(5); | |
stack.printStack(); | |
console.log('POPED :: '+ stack.pop()); | |
stack.push(6); | |
stack.printStack(); | |
console.log('PEEK :: '+ stack.peek()); | |
console.log('POPED :: '+ stack.pop()); | |
console.log('POPED :: '+ stack.pop()); | |
console.log('POPED :: '+ stack.pop()); | |
console.log('POPED :: '+ stack.pop()); | |
console.log('POPED :: '+ stack.pop()); | |
console.log('POPED :: '+ stack.pop()); |
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
"POPED :: Error: Underflow" | |
"PEEK :: 3" | |
5 | |
4 | |
3 | |
2 | |
1 | |
"POPED :: 5" | |
6 | |
4 | |
3 | |
2 | |
1 | |
"PEEK :: 6" | |
"POPED :: 6" | |
"POPED :: 4" | |
"POPED :: 3" | |
"POPED :: 2" | |
"POPED :: 1" | |
"POPED :: Error: Underflow" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment