Created
April 24, 2020 00:01
-
-
Save ashish-r/87164da0c0f6a85afffc74f094157830 to your computer and use it in GitHub Desktop.
Implementation of a Queue with the help of stacks in 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
class Stack { | |
constructor(size) { | |
this.size = size | |
this._stack = [] | |
} | |
push(val) { | |
if(this._stack.length > this.size) { | |
return | |
} | |
this._stack = [val, ...this._stack] | |
return val | |
} | |
pop() { | |
if(!this._stack.length) { | |
return | |
} | |
const out = this._stack[0] | |
this._stack = this._stack.splice(1) | |
return out | |
} | |
empty() { | |
this._stack = [] | |
} | |
count() { | |
return this._stack.length | |
} | |
} | |
class QueueWithStack { | |
constructor(size) { | |
this._queue1 = new Stack(size) | |
this._queue2 = new Stack(size) | |
this.size = size | |
} | |
enqueue(val) { | |
if(this._queue1.count() >= this.size) { | |
return | |
} | |
this._queue2.push(val) | |
let queue1Val = this._queue1.pop() | |
while(queue1Val) { | |
this._queue2.push(queue1Val) | |
queue1Val = this._queue1.pop() | |
} | |
let queue2Val = this._queue2.pop() | |
while(queue2Val) { | |
this._queue1.push(queue2Val) | |
queue2Val = this._queue2.pop() | |
} | |
this._queue2.empty() | |
return val | |
} | |
dequeue() { | |
if(!this._queue1.count()) { | |
return | |
} | |
let queue1Val = this._queue1.pop() | |
while(queue1Val) { | |
this._queue2.push(queue1Val) | |
queue1Val = this._queue1.pop() | |
} | |
const out = this._queue2.pop() | |
let queue2Val = this._queue2.pop() | |
while(queue2Val) { | |
this._queue1.push(queue2Val) | |
queue2Val = this._queue2.pop() | |
} | |
this._queue2.empty() | |
return out | |
} | |
} | |
const queue = new QueueWithStack(3) | |
queue.enqueue(1) | |
queue.enqueue(2) | |
queue.enqueue(3) | |
queue.dequeue() | |
queue.dequeue() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment