Created
March 25, 2023 00:47
-
-
Save fortunee/78944f106d597acbd18f4e2e4ff59b06 to your computer and use it in GitHub Desktop.
Stack
This file contains hidden or 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) { | |
this.first = newNode; | |
this.last = newNode; | |
} else { | |
const temp = this.first; | |
this.first = newNode; | |
this.first.next = temp; | |
} | |
return ++this.size; | |
} | |
pop() { | |
if (!this.first) return null; | |
const popped = this.first; | |
if (this.first === this.last) { | |
this.last = null; | |
} | |
this.first = popped.next; | |
this.size--; | |
return popped.value; | |
} | |
} | |
const stack = new Stack(); | |
// stack.push(12); | |
// stack.push(1); | |
stack.push(120); | |
stack.pop(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment