-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingQueues.java
More file actions
86 lines (74 loc) · 1.54 KB
/
StackUsingQueues.java
File metadata and controls
86 lines (74 loc) · 1.54 KB
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
80
81
82
83
84
85
86
package gfg.ds.stack;
import gfg.ds.stack.adt.Stack;
import java.util.ArrayDeque;
/** @noinspection WeakerAccess */
public class StackUsingQueues implements Stack {
private ArrayDeque<Integer> q1;
private ArrayDeque<Integer> q2;
private final boolean costlyPush;
public StackUsingQueues(boolean costlyPush) {
q1 = new ArrayDeque<>();
q2 = new ArrayDeque<>();
this.costlyPush = costlyPush;
}
@Override
public void push(int data) {
if (costlyPush) {
pushCostly(data);
} else {
pushEfficient(data);
}
}
private void pushCostly(int data) {
q2.add(data);
while (!q1.isEmpty()) {
q2.add(q1.poll());
}
// swapping references.
ArrayDeque<Integer> temp = q2;
q2 = q1;
q1 = temp;
}
private void pushEfficient(int data) {
q1.add(data);
}
@Override
public int pop() {
if (costlyPush) {
return popEfficient();
} else {
return popCostly();
}
}
private int popCostly() {
while (q1.size() != 1) {
q2.add(q1.poll());
}
int val = q1.pop();
// swapping references.
ArrayDeque<Integer> temp = q2;
q2 = q1;
q1 = temp;
return val;
}
private int popEfficient() {
assert !q1.isEmpty() : "Stack is empty";
return q1.poll();
}
@Override
public boolean isEmpty() {
return q1.isEmpty();
}
@Override
public int peek() {
int val;
if (costlyPush) {
val = popEfficient();
pushCostly(val);
} else {
val = popCostly();
pushEfficient(val);
}
return val;
}
}