-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderQueue.java
More file actions
49 lines (39 loc) · 1.04 KB
/
ReorderQueue.java
File metadata and controls
49 lines (39 loc) · 1.04 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
package Queue;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class ReorderQueue {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i < 9; i++) {
q.add(i);
}
Stack<Integer> st = new Stack<>();
int n = q.size();
// 1st Half in Stack.
for (int i = 1; i <= n / 2; i++) {
st.push(q.remove());
}
// 1st Half after 2nd but in reverse.
while (st.size() > 0) {
q.add(st.pop());
}
for (int i = 1; i <= n / 2; i++) {
st.push(q.remove());
}
// In Stack -> 8 7 6 5
// In Queue -> 4 3 2 1
for (int i = 1; i <= n / 2; i++) {
q.add(st.pop());
q.add(q.remove());
}
// Reverse the Queue.
while (q.size() > 0) {
st.push(q.remove());
}
while (st.size() > 0) {
q.add(st.pop());
}
System.out.println(q);
}
}