-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingStacks.java
More file actions
113 lines (99 loc) · 2.58 KB
/
Copy pathQueueUsingStacks.java
File metadata and controls
113 lines (99 loc) · 2.58 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package gfg.ds.queue;
import gfg.ds.queue.adt.Queue;
import java.util.ArrayDeque;
/** @noinspection WeakerAccess */
public class QueueUsingStacks implements Queue {
private final ArrayDeque<Integer> insertionStack, queryStack;
// Costly dequeue is better than costly enqueue as we have to move elements only one time.
private final boolean costlyEnqueue;
public QueueUsingStacks(boolean costlyEnqueue) {
insertionStack = new ArrayDeque<>();
queryStack = new ArrayDeque<>();
this.costlyEnqueue = costlyEnqueue;
}
/** t=O(1) */
@Override
public Queue enqueue(int data) {
if (costlyEnqueue) {
costlyEnqueue(data);
} else {
efficientEnqueue(data);
}
return this;
}
/** t=O(1) */
public int dequeue() {
assert !isEmpty() : "Queue is empty";
if (costlyEnqueue) {
return efficientDeqeue();
} else {
return costlyDequeue();
}
}
private void efficientEnqueue(int data) {
insertionStack.push(data);
}
private void costlyEnqueue(int data) {
while (!queryStack.isEmpty()) {
insertionStack.push(queryStack.pop());
}
insertionStack.push(data);
while (!insertionStack.isEmpty()) {
queryStack.push(insertionStack.pop());
}
}
private int costlyDequeue() {
if (queryStack.isEmpty()) {
while (!insertionStack.isEmpty()) {
queryStack.push(insertionStack.pop());
}
}
return queryStack.pop();
}
private int efficientDeqeue() {
return queryStack.pop();
}
/** t=O(1) */
@SuppressWarnings("ConstantConditions")
@Override
public int front() {
assert !isEmpty() : "Queue is empty";
if (costlyEnqueue) {
return queryStack.peek();
} else {
if (queryStack.isEmpty()) {
while (!insertionStack.isEmpty()) {
queryStack.push(insertionStack.pop());
}
}
return queryStack.peek();
}
}
/** t=O(1) */
@SuppressWarnings("ConstantConditions")
@Override
public int rear() {
assert !isEmpty() : "Queue is empty";
if (costlyEnqueue) {
while (!queryStack.isEmpty()) {
insertionStack.push(queryStack.pop());
}
int temp = insertionStack.peek();
while (!insertionStack.isEmpty()) {
queryStack.push(insertionStack.pop());
}
return temp;
} else {
if (insertionStack.isEmpty()) {
while (!queryStack.isEmpty()) {
insertionStack.push(queryStack.pop());
}
}
return insertionStack.peek();
}
}
/** t=O(1) */
public boolean isEmpty() {
return insertionStack.isEmpty() && queryStack.isEmpty();
}
}