-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0225-implement-stack-using-queues.js
More file actions
40 lines (34 loc) · 991 Bytes
/
0225-implement-stack-using-queues.js
File metadata and controls
40 lines (34 loc) · 991 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
38
39
40
/**
* Implement Stack Using Queues
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var MyStack = function () {
this.primaryStorage = [];
this.secondaryStorage = [];
};
MyStack.prototype.push = function (x) {
this.secondaryStorage.push(x);
let primaryQueueLength = this.primaryStorage.length;
let loopIndex = 0;
while (loopIndex < primaryQueueLength) {
let transferredItem = this.primaryStorage.shift();
this.secondaryStorage.push(transferredItem);
loopIndex++;
}
let temporaryReference = this.primaryStorage;
this.primaryStorage = this.secondaryStorage;
this.secondaryStorage = temporaryReference;
};
MyStack.prototype.pop = function () {
let removedValue = this.primaryStorage.shift();
return removedValue;
};
MyStack.prototype.top = function () {
let peekedValue = this.primaryStorage[0];
return peekedValue;
};
MyStack.prototype.empty = function () {
let isEmptyResult = this.primaryStorage.length === 0;
return isEmptyResult;
};