Skip to content

Commit 6d1eb10

Browse files
authored
Create Queue-Reverse the First K Elements in the Queue
1 parent beeb3fe commit 6d1eb10

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
For a given queue containing all integer data, reverse the first K elements.
2+
You have been required to make the desired change in the input queue itself.
3+
Example:
4+
alt txt
5+
6+
For the above input queue, if K = 4 then after reversing the first 4 elements, the queue will be updated as:
7+
alt txt
8+
9+
Input Format :
10+
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.
11+
12+
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.
13+
Output Format:
14+
The only line of output prints the updated order in which the queue elements are dequeued, all of them separated by a single space.
15+
Note:
16+
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.
17+
Constraints :
18+
1 <= N <= 10^6
19+
1 <= K <= N
20+
-2^31 <= data <= 2^31 - 1
21+
22+
Time Limit: 1sec
23+
Sample Input 1:
24+
5 3
25+
1 2 3 4 5
26+
Sample Output 1:
27+
3 2 1 4 5
28+
Sample Input 2:
29+
7 7
30+
3 4 2 5 6 7 8
31+
Sample Output 2:
32+
8 7 6 5 2 4 3
33+
34+
*******************************************Code*********************************************
35+
import java.util.*;
36+
37+
public class Solution {
38+
39+
public static Queue<Integer> reverseKElements(Queue<Integer> input, int k) {
40+
41+
Queue<Integer> q1=new LinkedList<>();
42+
for(int i=0;i<k;i++)
43+
{
44+
q1.add(input.poll());
45+
}
46+
Collections.reverse((List<?>)q1);
47+
int len=input.size();
48+
for(int i=0;i<len;i++)
49+
{
50+
q1.add(input.poll());
51+
}
52+
return q1;
53+
}
54+
public static Queue<Integer> reverseQueue(Queue<Integer> input)
55+
{
56+
if (input.size() <= 1)
57+
return input;
58+
int f = input.poll();
59+
reverseQueue(input);
60+
input.add(f);
61+
return input;
62+
}
63+
}

0 commit comments

Comments
 (0)