-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathenqueueDequeueWithStacks.js
72 lines (54 loc) · 1.23 KB
/
enqueueDequeueWithStacks.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
class Stack {
constructor() {
this.array = [];
}
isEmpty() {
return this.array.length === 0;
}
peek() {
if (this.isEmpty()) {
return null;
} else {
return this.array[this.array.length - 1];
}
}
push(value) {
this.array.push(value);
}
pop() {
if (this.isEmpty()) return null;
return this.array.pop();
}
}
class MyQueue {
constructor() {
this.stack1 = new Stack();
this.stack2 = new Stack();
}
peek() {
return this.stack1.peek();
}
isEmpty() {
return this.stack1.isEmpty();
}
enqueue(value) {
while(!this.stack1.isEmpty()) {
this.stack2.push(this.stack1.pop());
}
this.stack2.push(value);
while(!this.stack2.isEmpty()) {
this.stack1.push(this.stack2.pop());
}
}
dequeue() {
if(this.stack1.isEmpty()) return null;
return this.stack1.pop();
}
}
const queue = new MyQueue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log("Top element: ", queue.peek()); // 3
queue.dequeue(3);
console.log("Top element: ", queue.peek()); // 2