-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP27.java
More file actions
56 lines (45 loc) · 1.22 KB
/
P27.java
File metadata and controls
56 lines (45 loc) · 1.22 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
package stack_and_queue;
// Java program to reverse a Queue by recursion
import java.util.LinkedList;
import java.util.Queue;
// Java program to reverse a queue recursively
public class P27 {
static Queue<Integer> queue;
// Utility function to print the queue
static void Print() {
while (!queue.isEmpty()) {
System.out.print(queue.peek() + " ");
queue.remove();
}
}
// Recurrsive function to reverse the queue
static Queue<Integer> reverseQueue(Queue<Integer> q) {
// Base case
if (q.isEmpty())
return q;
// Dequeue current item (from front)
int data = q.peek();
q.remove();
// Reverse remaining queue
q = reverseQueue(q);
// Enqueue current item (to rear)
q.add(data);
return q;
}
// Driver code
public static void main(String args[]) {
queue = new LinkedList<Integer>();
queue.add(56);
queue.add(27);
queue.add(30);
queue.add(45);
queue.add(85);
queue.add(92);
queue.add(58);
queue.add(80);
queue.add(90);
queue.add(100);
queue = reverseQueue(queue);
Print();
}
}