Created
March 20, 2022 11:40
-
-
Save mustafadalga/1f448b3c2146aad6769f147a48aedf01 to your computer and use it in GitHub Desktop.
Stack Data Structure Example
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(value) { | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class Stack { | |
constructor() { | |
this.first = null; | |
this.last = null; | |
this.size = 0; | |
} | |
push(value) { | |
const newNode = new Node(value); | |
if (this.first) { | |
newNode.next = this.first; | |
this.first = newNode; | |
} else { | |
this.first = newNode; | |
this.last = newNode; | |
} | |
this.size++; | |
return this.size; | |
} | |
pop() { | |
if (!this.size) return null; | |
const removedNode = this.first; | |
if (this.first == this.last) { | |
this.last = null; | |
} | |
this.first = removedNode.next; | |
this.size--; | |
return removedNode.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment