Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Last active February 1, 2023 06:33
Show Gist options
  • Save jordanrios94/1588154decfcb8617b6f6324c8af2da4 to your computer and use it in GitHub Desktop.
Save jordanrios94/1588154decfcb8617b6f6324c8af2da4 to your computer and use it in GitHub Desktop.
Coding Exercise - Queue From Stacks
/*
Implement a Queue data structure using two stacks.
- Do not create an array inside of the 'Queue' class.
- Queue should implement the methods 'add', 'remove', and 'peek'.
*/
class Stack {
constructor() {
this.data = [];
}
push(record) {
this.data.push(record);
}
pop() {
return this.data.pop();
}
peek() {
return this.data[this.data.length - 1];
}
}
class Queue {
constructor() {
this.dataOne = new Stack();
this.dataTwo = new Stack();
}
add(item) {
this.dataOne.push(item);
}
remove() {
while(this.dataOne.peek()) {
this.dataTwo.push(this.dataOne.pop());
}
const item = this.dataTwo.pop();
while (this.dataTwo.peek()) {
this.dataOne.push(this.dataTwo.pop())
}
return item;
}
peek() {
while(this.dataOne.peek()) {
this.dataTwo.push(this.dataOne.pop());
}
const item = this.dataTwo.peek();
while (this.dataTwo.peek()) {
this.dataOne.push(this.dataTwo.pop())
}
return item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment