Skip to content

Instantly share code, notes, and snippets.

@tdubs42
Created February 19, 2024 04:37
Show Gist options
  • Save tdubs42/56a198e7ebf8e1b416863fc216ce58fd to your computer and use it in GitHub Desktop.
Save tdubs42/56a198e7ebf8e1b416863fc216ce58fd to your computer and use it in GitHub Desktop.
Stack Class - JavaScript
const LinkedList = require('./LinkedList');
class Stack {
constructor(maxSize = Infinity) {
this.stack = new LinkedList();
this.maxSize = maxSize;
this.size = 0;
}
// Add helper methods below this line
hasRoom() {
return this.size < this.maxSize;
}
isEmpty() {
return this.size === 0;
}
push(value) {
if (this.hasRoom()) {
this.stack.addToHead(value);
this.size++;
} else {
throw new Error('Stack is full');
}
}
pop() {
if (!this.isEmpty()) {
const value = this.stack.removeHead();
this.size--;
return value;
} else {
throw new Error('Stack is empty');
}
}
peek() {
if (!this.isEmpty()) {
return this.stack.head.data;
} else {
return null;
}
}
}
module.exports = Stack;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment