-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathqueue-via-stacks.js
59 lines (54 loc) · 1.25 KB
/
queue-via-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
class MyQueue {
constructor() {
this.stackNewest = new Stack();
this.stackOldest = new Stack();
}
size() {
return this.stackNewest.size() + this.stackOldest.size();
}
push(x) {
/* Push into stackNewest; wich always has the newes elements on top */
this.stackNewest.push(x);
}
/* muve elements from stackNewest into stackOldest. This is usually done so that
we can do operations on stackOldest. */
#shiftStacks() {
if (this.stackOldest.isEmpty()) {
while (!this.stackNewest.isEmpty()) {
this.stackOldest.push(this.stackNewest.pop());
}
}
}
pop() {
this.#shiftStacks(); // Ensure stackOldest has the current elements
return this.stackOldest.pop();
}
peek() {
this.#shiftStacks(); // Ensure stackOldest has the current elements
return this.stackOldest.peek();
}
empty() {
return this.stackNewest.size() + this.stackOldest.size() === 0;
}
}
class Stack {
constructor() {
this.data = [];
}
size() {
return this.data.length;
}
isEmpty() {
return this.size() === 0;
}
push(value) {
this.data.push(value);
}
pop() {
return this.data.pop();
}
peek() {
if (this.isEmpty()) return null;
return this.data[this.size() - 1];
}
}