Skip to content

Instantly share code, notes, and snippets.

@fortunee
Created March 25, 2023 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fortunee/78944f106d597acbd18f4e2e4ff59b06 to your computer and use it in GitHub Desktop.
Save fortunee/78944f106d597acbd18f4e2e4ff59b06 to your computer and use it in GitHub Desktop.
Stack
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