Created
January 17, 2020 08:32
-
-
Save tjbulick/0eb0c46f2df60cfb583620f97208b2c9 to your computer and use it in GitHub Desktop.
Implementation of Queue data structure using two stacks in JavaScript. Actually, it uses two arrays here(because there is no stack in JavaScript), but you should have a look at your language docs: perhaps it provides embedded stack data structure. (For example: Java provides class "Stack", C# similarly, etc.)
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
class Queue { | |
constructor() { | |
this.inbox = []; | |
this.outbox = []; | |
} | |
enqueue(item) { | |
this.inbox.push(item); | |
} | |
dequeue() { | |
while(this.inbox.length) { | |
this.outbox.push(this.inbox.pop()); | |
} | |
const returnable = this.outbox.pop(); | |
while(this.outbox.length) { | |
this.inbox.push(this.outbox.pop()); | |
} | |
return returnable; | |
} | |
} | |
const queue = new Queue(); | |
queue.enqueue(1); | |
queue.enqueue(3); | |
queue.enqueue(7); | |
queue.dequeue(); | |
queue.dequeue(); | |
queue.dequeue(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can we approach for O(N) for enqueue and O(1) for dequeue.
And what to do for front() in Queue, to get the peek element using peek() of Stack.