Last active
September 5, 2022 03:16
-
-
Save dashsaurabh/baa610b5626386b8d49d57a142f1e0e1 to your computer and use it in GitHub Desktop.
Stack Implementation in Javascript
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 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 aNode
class too.