Created
April 1, 2020 03:36
-
-
Save JustAyush/cf2491b1261354cbe28375207aff9cd4 to your computer and use it in GitHub Desktop.
Implementation of Stack in JavaScript
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
// Try edit message | |
class Node { | |
constructor (value, nextNode) { | |
this.value = value, | |
this.nextNode = nextNode | |
} | |
} | |
class Stack { | |
constructor () { | |
this.top = null; | |
} | |
push (value) { | |
let newNode = new Node(value, this.top); | |
this.top = newNode; | |
console.log('PUSH'); | |
this.print(); | |
} | |
pop () { | |
let nodeToRemove = null; | |
if(this.top) { | |
nodeToRemove = this.top; | |
this.top = this.top.nextNode; | |
} | |
console.log('PULL'); | |
this.print(); | |
return nodeToRemove; | |
} | |
print() { | |
let ptr = this.top; // has to be referenced. Directly editing this.top won't work | |
while(ptr != null) { | |
console.log(ptr.value); | |
ptr = ptr.nextNode; | |
} | |
} | |
} | |
let s = new Stack(); | |
s.push(1); | |
s.push(2); | |
s.push(3); | |
s.pop(); | |
s.pop(); | |
s.pop(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment