Skip to content

Instantly share code, notes, and snippets.

@JustAyush
Created April 1, 2020 03:36
Show Gist options
  • Save JustAyush/cf2491b1261354cbe28375207aff9cd4 to your computer and use it in GitHub Desktop.
Save JustAyush/cf2491b1261354cbe28375207aff9cd4 to your computer and use it in GitHub Desktop.
Implementation of Stack in JavaScript
// 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