-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0232-implement-queue-using-stacks.js
More file actions
41 lines (37 loc) · 1.01 KB
/
0232-implement-queue-using-stacks.js
File metadata and controls
41 lines (37 loc) · 1.01 KB
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
38
39
40
41
/**
* Implement Queue Using Stacks
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
var MyQueue = function () {
this.inputStack = [];
this.outputStack = [];
};
MyQueue.prototype.push = function (x) {
this.inputStack.push(x);
};
MyQueue.prototype.pop = function () {
if (this.outputStack.length === 0) {
while (this.inputStack.length > 0) {
let elementFromInput = this.inputStack.pop();
this.outputStack.push(elementFromInput);
}
}
let retrievedElement = this.outputStack.pop();
return retrievedElement;
};
MyQueue.prototype.peek = function () {
if (this.outputStack.length === 0) {
while (this.inputStack.length > 0) {
let transferredItem = this.inputStack.pop();
this.outputStack.push(transferredItem);
}
}
let frontOfQueue = this.outputStack[this.outputStack.length - 1];
return frontOfQueue;
};
MyQueue.prototype.empty = function () {
let currentEmptyState =
this.inputStack.length === 0 && this.outputStack.length === 0;
return currentEmptyState;
};