-
Notifications
You must be signed in to change notification settings - Fork 0
/
232. Implement queue using stacks.js
76 lines (54 loc) · 1.36 KB
/
232. Implement queue using stacks.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import * as Utils from './Utils.js';
/**
* Implement a first in first out (FIFO) queue using only two stacks.
* The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
*/
class MyQueue {
inStack = [];
outStack = [];
push(item) {
this.inStack.push(item);
}
pop() {
if (this.outStack.length === 0) {
this.fillOutStack();
}
return this.outStack.pop();
}
peek() {
if (this.outStack.length === 0) {
this.fillOutStack();
}
return this.outStack[this.outStack.length-1];
}
empty() {
return this.inStack.length === 0 && this.outStack.length === 0;
}
toString() {
return [...this.outStack].reverse().concat(this.inStack).toString();
}
fillOutStack() {
while(this.inStack.length !== 0) {
this.outStack.push(this.inStack.pop());
}
}
}
// Test cases
const testQueue = new MyQueue();
testQueue.push(2);
testQueue.push(9);
testQueue.push(1);
testQueue.push(5);
console.log(testQueue.toString());
console.assert(testQueue.peek() === 2);
console.assert(testQueue.pop() === 2);
console.log(testQueue.toString());
console.assert(testQueue.peek() === 9);
testQueue.push(6);
console.assert(!testQueue.empty());
console.log(testQueue.toString());
testQueue.pop();
testQueue.pop();
testQueue.pop();
testQueue.pop();
console.assert(testQueue.empty());