-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path232. Implement Queue using Stacks.js
71 lines (62 loc) · 1.23 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
/**
* @constructor
*/
class Queue {
constructor() {
this.stack1 = [];
this.stack2 = [];
this.length = 0;
}
/**
* @param {number} x
* @returns {void}
*/
push(x) {
this.stack1.push(x);
this.length++;
}
/**
* @returns {void}
*/
pop() {
this.adjust();
this.stack2.pop();
this.length--;
}
/**
* @returns {number}
*/
peek() {
this.adjust();
return this.stack2[this.stack2.length - 1];
}
/**
* @returns {boolean}
*/
empty() {
if (this.length === 0) {
return true;
} else {
return false;
}
}
/**
* @returns {void}
*/
adjust() {
if (this.stack2.length === 0) {
while (this.stack1.length !== 0) {
this.stack2.push(this.stack1.pop());
}
}
}
}
let test = new Queue();
test.push(3);
console.log(`stack1: ${test.stack1}`);
console.log(`stack2: ${test.stack2}`);
console.log(test.empty());
test.pop();
console.log(`stack1: ${test.stack1}`);
console.log(`stack2: ${test.stack2}`);
console.log(test.empty());