Skip to content

Instantly share code, notes, and snippets.

@tjbulick
Created January 17, 2020 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tjbulick/0eb0c46f2df60cfb583620f97208b2c9 to your computer and use it in GitHub Desktop.
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.)
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();
@th3qui85ly
Copy link

th3qui85ly commented Nov 26, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment