-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathReverse_First_K_elements_of_Queue.java
More file actions
68 lines (56 loc) · 1.55 KB
/
Reverse_First_K_elements_of_Queue.java
File metadata and controls
68 lines (56 loc) · 1.55 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
57
58
59
60
61
62
63
64
65
66
67
68
// { Driver Code Starts
// Initial Template for Java
import java.util.*;
class ModifyQueue {
public static void main(String[] args) {
// Taking input using class Scanner
Scanner sc = new Scanner(System.in);
// Taking total number of testcases
int t = sc.nextInt();
while (t-- > 0) {
// Taking count of total number of elements
int n = sc.nextInt();
// Taking count of total elements
// that need to be reversed
int k = sc.nextInt();
// Creating a Queue
Queue<Integer> q = new LinkedList<>();
// adding all the elements to the Queue
while (n-- > 0) {
q.add((int) sc.nextInt());
}
// Creating an object of class GfG
GfG g = new GfG();
// calling modifyQueue of class GfG
// and passing Queue and k as arguments
// and storing the reuslt in a new Queue
Queue<Integer> ans = g.modifyQueue(q, k);
// Printing all the elements from the
// new Queue and polling them out
while (!ans.isEmpty()) {
int a = ans.peek();
ans.poll();
System.out.print(a + " ");
}
System.out.println();
}
}
}
class GfG {
// Function to reverse first k elements of a queue.
public Queue<Integer> modifyQueue(Queue<Integer> q, int k) {
Stack<Integer> s = new Stack<Integer>();
int n = q.size();
for (int i = 0; i < k; i++) {
s.push(q.poll());
}
while (!s.isEmpty()) {
q.add(s.pop());
}
int rem = n - k;
while (rem-- > 0) {
q.add(q.poll());
}
return q;
}
}