-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseFirstK.java
More file actions
38 lines (31 loc) · 851 Bytes
/
ReverseFirstK.java
File metadata and controls
38 lines (31 loc) · 851 Bytes
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
package Queue;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class ReverseFirstK {
public static Queue<Integer> modifyQueue(Queue<Integer> q, int k) {
Stack<Integer> st = new Stack<>();
while (st.size() != k) {
st.push(q.remove());
}
while (st.size() != 0) {
q.add(st.pop());
}
int temp = q.size() - k;
while (temp > 0) {
q.add(q.remove());
temp--;
}
return q;
}
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i <= 5; i++) {
q.add(i);
}
Queue<Integer> ans = modifyQueue(q, 3);
for (int i = 0; i < 5; i++) {
System.out.print(ans.poll() + " ");
}
}
}