Created
March 3, 2020 07:36
-
-
Save zaingz/fbb9aff467ef297db0cae1f8398e4a0e to your computer and use it in GitHub Desktop.
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 = []; | |
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