Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.8 kB
0
Indexable
Never
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of integers: ");
        int numIntegers = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        System.out.print("Enter the value of K: ");
        int k = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        Queue<Integer> queue = new LinkedList<>();

        System.out.println("Enter " + numIntegers + " integers:");
        for (int i = 0; i < numIntegers; i++) {
            int num = scanner.nextInt();
            queue.add(num);
        }

        System.out.println("Original queue: " + queue);
        reverseKElements(queue, k);
        System.out.println("After reversing first " + k + " elements: " + queue);

        scanner.close(); // Close the scanner
    }

    public static void reverseKElements(Queue<Integer> queue, int k) {
        if (k <= 0 || k > queue.size()) {
            return; // Invalid input
        }

        Stack<Integer> stack = new Stack<>();

        // Push the first K elements of the queue into a stack
        for (int i = 0; i < k; i++) {
            stack.push(queue.poll());
        }

        // Pop elements from the stack and enqueue them back into the queue
        while (!stack.isEmpty()) {
            queue.add(stack.pop());
        }

        // Dequeue and enqueue the remaining elements to maintain order
        for (int i = 0; i < queue.size() - k; i++) {
            queue.add(queue.poll());
        }
    }
}