Created
February 19, 2024 04:37
-
-
Save tdubs42/56a198e7ebf8e1b416863fc216ce58fd to your computer and use it in GitHub Desktop.
Stack Class - JavaScript
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
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