Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created March 20, 2022 11:40
Show Gist options
  • Save mustafadalga/1f448b3c2146aad6769f147a48aedf01 to your computer and use it in GitHub Desktop.
Save mustafadalga/1f448b3c2146aad6769f147a48aedf01 to your computer and use it in GitHub Desktop.
Stack Data Structure Example
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