-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathReverseQueue.java
47 lines (45 loc) · 1.03 KB
/
ReverseQueue.java
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
package SummerTrainingGFG.Queue;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;
/**
* @author Vishal Singh
*/
public class ReverseQueue {
/*
* Iterative Approach
* Explicitly Using stack
* */
static void reverse(Queue<Integer> q){
Stack<Integer> s = new Stack<>();
while (!q.isEmpty()){
s.push(q.remove());
}
while (!s.isEmpty()){
q.offer(s.pop());
}
}
/*
* Recursice approach
* Functional Stack used internally
* */
static void reverseRecursive(Queue<Integer> q){
if (q.isEmpty()){
return;
}
int top = q.poll();
reverseRecursive(q);
q.offer(top);
}
public static void main(String[] args) {
Queue<Integer> q = new ArrayDeque<>();
q.offer(3);
q.offer(2);
q.offer(1);
System.out.println(q);
reverse(q);
System.out.println(q);
reverseRecursive(q);
System.out.println(q);
}
}