Skip to content

Instantly share code, notes, and snippets.

@zaingz
Created March 3, 2020 07:36
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 zaingz/fbb9aff467ef297db0cae1f8398e4a0e to your computer and use it in GitHub Desktop.
Save zaingz/fbb9aff467ef297db0cae1f8398e4a0e to your computer and use it in GitHub Desktop.
class Stack {
constructor() {
this.items = [];
this.top = null;
}
getTop() {
if (this.items.length == 0)
return null;
return this.top;
}
isEmpty() {
return this.items.length == 0;
}
size() {
return this.items.length;
}
push(element) {
this.items.push(element);
this.top = element;
}
pop() {
if (this.items.length != 0) {
if (this.items.length == 1) {
this.top = null;
return this.items.pop();
} else {
this.top = this.items[this.items.length - 2];
return this.items.pop();
}
} else
return null;
}
}
var myStack = new Stack();
for (var i = 0; i < 5; i++) {
myStack.push(i);
}
console.log("Is stack empty? " + myStack.isEmpty());
console.log("top: " + myStack.getTop());
for (var i = 0; i < 5; i++) {
console.log("Element popped: " + myStack.pop());
console.log("top: " + myStack.getTop());
}
console.log("Is stack empty?: " + myStack.isEmpty());
console.log("top: " + myStack.getTop());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment