Skip to content

Instantly share code, notes, and snippets.

@dashsaurabh
Last active September 5, 2022 03:16
Show Gist options
  • Save dashsaurabh/baa610b5626386b8d49d57a142f1e0e1 to your computer and use it in GitHub Desktop.
Save dashsaurabh/baa610b5626386b8d49d57a142f1e0e1 to your computer and use it in GitHub Desktop.
Stack Implementation in Javascript
class Node {
constructor(val){
this.val = val;
this.next = null;
}
}
class Stack {
constructor(){
this.first = null;
this.last = null;
this.length = 0;
}
push(val){
let newNode = new Node(val)
if (this.length === 0){
this.first = newNode;
this.last = newNode;
}else{
let temp = this.first;
this.first = newNode;
this.first.next= temp;
}
this.length++;
return this.length;
}
pop(){
if (this.length === 0) return null;
let temp = this.first;
if (this.length === 1){
this.last = null;
}
this.first = this.first.next;
this.length--;
return temp;
}
}
@a-hamouda
Copy link

Thank you for that.

For anyone looking to use this implementation in a project alongside Bootstrap, please change the name of Node class. Otherwise Bootstrap components will not work properly because Bootstrap has a Node class too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment