Created
April 7, 2021 22:30
-
-
Save RomanTurner/a82889b056f34967effae11176410b15 to your computer and use it in GitHub Desktop.
Stack 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 Stack { | |
constructor(){ | |
this.length = 0; | |
this.head = null; | |
} | |
//Push data in the stack | |
push = (el) => { | |
//Create a new node | |
let node = new Node(el), | |
current; | |
//Add the new node at the top | |
current = this.head; | |
node.next = current; | |
this.head = node; | |
this.length++; | |
} | |
//Pop the item from the stack | |
pop = () => { | |
let current = this.head; | |
//If there is item then remove it | |
//and make the next element as the first | |
if(current){ | |
let el = current.element; | |
current = current.next; | |
this.head = current; | |
this.length--; | |
return el; | |
} | |
return null; | |
} | |
//Return the first element in the stack | |
peek = () => { | |
if(this.head){ | |
return this.head.element; | |
} | |
return null; | |
} | |
//Convert the stack to an array | |
toArray = () => { | |
let arr = []; | |
let current = this.head; | |
while(current){ | |
arr.push(current.element); | |
current = current.next; | |
} | |
return arr; | |
} | |
//Check if stack is empty | |
isEmpty = () => { | |
return this.length === 0; | |
} | |
//Return the size of the stack | |
size = () => { | |
return this.length; | |
} | |
//Clear the stack | |
clear = () => { | |
this.head = null; | |
this.length = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment