-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterleave_twoHalves_ofQueue.java
More file actions
51 lines (38 loc) · 1.01 KB
/
Interleave_twoHalves_ofQueue.java
File metadata and controls
51 lines (38 loc) · 1.01 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
package Queue;
import java.util.*;
public class Interleave_twoHalves_ofQueue {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
q.add(5);
q.add(6);
q.add(7);
q.add(8);
q.add(9);
q.add(10);
interleave(q);
while (!q.isEmpty()){
System.out.print(q.peek() + " " );
q.remove();
}
}
private static void interleave(Queue<Integer> q) {
Queue<Integer> q2 = new LinkedList<>();
int n = q.size();
int i = 1;
// add halve elements from front to new queue
while (i <= n/2){
q2.add(q.remove());
i++;
}
// add to old que side by side
int front = q2.peek();
while (front != q.peek()){
q.add(q2.remove());
q.add(q.remove());
}
}
}