Skip to content

Instantly share code, notes, and snippets.

@rshivkumar95
Last active July 21, 2019 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rshivkumar95/5f57d38f2d196692a0aab8c3fabff5d8 to your computer and use it in GitHub Desktop.
Save rshivkumar95/5f57d38f2d196692a0aab8c3fabff5d8 to your computer and use it in GitHub Desktop.
Stack Implementation using ES6
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());
"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