Untitled
unknown
plain_text
a year ago
2.7 kB
7
Indexable
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack; public class App { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the value of K: "); int K = scanner.nextInt(); Queue<Integer> queue = new LinkedList<>(); Stack<Integer> stack = new Stack<>(); // Populate the queue System.out.println("Enter integers to populate the queue:"); for (int i = 0; i < K; i++) { int element = scanner.nextInt(); enqueue(queue, element); } reverseFirstKElements(queue, K, stack); System.out.println("Queue after reversing first " + K + " elements:"); while (!isEmpty(queue)) { System.out.print(front(queue) + " "); dequeue(queue); } } // Function to reverse the first K elements of a queue public static void reverseFirstKElements(Queue<Integer> queue, int K, Stack<Integer> stack) { if (isEmpty(queue) || K <= 0 || K > size(queue)) { System.out.println("Invalid input for K"); return; } // Dequeue the first K elements from the original queue into the stack for (int i = 0; i < K; i++) { int element = front(queue); dequeue(queue); stack.push(element); } // Enqueue the elements back into the original queue in reversed order while (!stack.isEmpty()) { int element = stack.pop(); enqueue(queue, element); } } // Custom enqueue operation to add an item to the rear of the queue public static void enqueue(Queue<Integer> queue, int x) { queue.add(x); } // Custom dequeue operation to remove an item from the front of the queue public static void dequeue(Queue<Integer> queue) { if (!isEmpty(queue)) { queue.poll(); } } // Custom size operation to return the number of elements in the queue public static int size(Queue<Integer> queue) { return queue.size(); } // Custom front operation to find the front item of the queue public static int front(Queue<Integer> queue) { if (!isEmpty(queue)) { return queue.peek(); } return -1; // Return -1 if the queue is empty (you can choose any sentinel value) } // Custom isEmpty operation to check if the queue is empty public static boolean isEmpty(Queue<Integer> queue) { return queue.isEmpty(); } }
Editor is loading...