-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueWithStack.js
79 lines (58 loc) · 1.57 KB
/
QueueWithStack.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
76
77
78
79
class QueueWithStack {
constructor() {
this.stack1 = [];
this.stack2 = [];
}
enqueue(value) {
this.stack1.push(value);
}
dequeue() {
if (this.stack1.length === 0 && this.stack2.length === 0) {
return null;
}
if (this.stack2.length === 0) {
while (this.stack1.length > 0) {
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop();
}
front() {
if (this.stack1.length === 0 && this.stack2.length === 0) {
return null;
}
if (this.stack2.length === 0) {
while (this.stack1.length > 0) {
this.stack2.push(this.stack1.pop());
}
}
return this.stack2[this.stack2.length - 1];
}
isEmpty() {
return this.stack1.length === 0 && this.stack2.length === 0;
}
print() {
if (this.isEmpty()) {
console.log("Queue is empty.");
return;
}
console.log("Queue elements (front to rear):");
if (this.stack2.length === 0) {
while (this.stack1.length > 0) {
this.stack2.push(this.stack1.pop());
}
}
for (let i = this.stack2.length - 1; i >= 0; i--) {
console.log(this.stack2[i]);
}
console.log("Front of the queue:", this.front());
}
}
const queue = new QueueWithStack();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.print();
console.log(queue.dequeue());
queue.enqueue(4);
queue.print();