-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseFirstKElement.java
More file actions
55 lines (44 loc) · 1.58 KB
/
Copy pathReverseFirstKElement.java
File metadata and controls
55 lines (44 loc) · 1.58 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
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class ReverseFirstKElement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
Queue<Integer> queue = new LinkedList<>();
// Input queue elements
System.out.print("Enter the queue elements: ");
for (int i = 0; i < n; i++) {
queue.add(scanner.nextInt());
}
System.out.print("Enter the number of elements to reverse: ");
int k = scanner.nextInt();
// Reverse the first k elements of the queue
reverseFirstK(queue, k);
// Print the modified queue
System.out.print("Modified queue: ");
while (!queue.isEmpty()) {
System.out.print(queue.remove() + " ");
}
}
private static void reverseFirstK(Queue<Integer> queue, int k) {
if (queue.isEmpty() || k < 0 || k > queue.size()) {
return;
}
// Create a stack to store the first k elements of the queue
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < k; i++) {
stack.push(queue.remove());
}
// Enqueue the reversed elements from the stack to the queue
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
// Enqueue the remaining elements to the queue
for (int i = 0; i < queue.size() - k; i++) {
queue.add(queue.remove());
}
}
}