forked from jmcilhargey/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchpt3-queue-via-stacks.js
More file actions
37 lines (31 loc) · 1013 Bytes
/
chpt3-queue-via-stacks.js
File metadata and controls
37 lines (31 loc) · 1013 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Our task is to build a queue using 2 stacks -- Queue is FIFO while stack is LIFO
// We use the left one to deposit new values and then the right one to reverse them so they're in order
function Queue() {
this.leftStack = [];
this.rightStack = [];
}
Queue.prototype.add = function(value) {
this.leftStack.push(value);
};
Queue.prototype.remove = function() {
// If our queue stack is empty we'll need to push things from the push stack
if (!this.rightStack.length) {
this.dequeue();
}
return this.rightStack.pop();
};
Queue.prototype.dequeue = function() {
// Move everything from the push stack to the pop stack -- This gets us the elements in order
while (this.leftStack.length) {
this.rightStack.push(this.leftStack.pop());
}
};
Queue.prototype.size = function() {
return this.leftStack.length + this.rightStack.length;
};
Queue.prototype.peek = function() {
if (!this.rightStack.length) {
this.dequeue();
}
return this.rightStack[this.rightStack.length - 1];
};