-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue-Reverse the First K Elements in the Queue
63 lines (55 loc) · 1.78 KB
/
Queue-Reverse the First K Elements in the Queue
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
For a given queue containing all integer data, reverse the first K elements.
You have been required to make the desired change in the input queue itself.
Example:
alt txt
For the above input queue, if K = 4 then after reversing the first 4 elements, the queue will be updated as:
alt txt
Input Format :
The first line of input would contain two integers N and K, separated by a single space. They denote the total number of elements in the queue and the count with which the elements need to be reversed respectively.
The second line of input contains N integers separated by a single space, representing the order in which the elements are enqueued into the queue.
Output Format:
The only line of output prints the updated order in which the queue elements are dequeued, all of them separated by a single space.
Note:
You are not required to print the expected output explicitly, it has already been taken care of. Just make the changes in the input queue itself.
Constraints :
1 <= N <= 10^6
1 <= K <= N
-2^31 <= data <= 2^31 - 1
Time Limit: 1sec
Sample Input 1:
5 3
1 2 3 4 5
Sample Output 1:
3 2 1 4 5
Sample Input 2:
7 7
3 4 2 5 6 7 8
Sample Output 2:
8 7 6 5 2 4 3
*******************************************Code*********************************************
import java.util.*;
public class Solution {
public static Queue<Integer> reverseKElements(Queue<Integer> input, int k) {
Queue<Integer> q1=new LinkedList<>();
for(int i=0;i<k;i++)
{
q1.add(input.poll());
}
Collections.reverse((List<?>)q1);
int len=input.size();
for(int i=0;i<len;i++)
{
q1.add(input.poll());
}
return q1;
}
public static Queue<Integer> reverseQueue(Queue<Integer> input)
{
if (input.size() <= 1)
return input;
int f = input.poll();
reverseQueue(input);
input.add(f);
return input;
}
}