-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackWithQueue
74 lines (55 loc) · 1.3 KB
/
StackWithQueue
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
class StackWithQueue {
constructor() {
this.queue1 = [];
this.queue2 = [];
}
push(value) {
this.queue1.push(value);
}
pop() {
if (this.queue1.length === 0) {
return null;
}
while (this.queue1.length > 1) {
this.queue2.push(this.queue1.shift());
}
const poppedValue = this.queue1.shift();
[this.queue1, this.queue2] = [this.queue2, this.queue1];
return poppedValue;
}
top() {
if (this.queue1.length === 0) {
return null;
}
while (this.queue1.length > 1) {
this.queue2.push(this.queue1.shift());
}
const topValue = this.queue1[0];
this.queue2.push(this.queue1.shift());
[this.queue1, this.queue2] = [this.queue2, this.queue1];
return topValue;
}
isEmpty() {
return this.queue1.length === 0;
}
print() {
if (this.queue1.length === 0) {
console.log("Stack is empty.");
return;
}
console.log("Stack elements:");
for (let i = this.queue1.length - 1; i >= 0; i--) {
console.log(this.queue1[i]);
}
console.log("Top value:", this.top());
}
}
const stack = new StackWithQueue();
stack.push(1);
stack.push(2);
stack.push(3);
stack.print();
stack.pop();
stack.print();
stack.top();
stack.print();