Last active
February 1, 2023 06:33
-
-
Save jordanrios94/1588154decfcb8617b6f6324c8af2da4 to your computer and use it in GitHub Desktop.
Coding Exercise - Queue From Stacks
This file contains hidden or 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
/* | |
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