Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.1 kB
1
Indexable
Never
import java.util.LinkedList;
import java.util.Queue;
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();
            enqueue(queue, 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 enqueue(Queue<Integer> queue, int x) {
        queue.add(x);
    }

    public static int dequeue(Queue<Integer> queue) {
        if (queue.isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        return queue.poll();
    }

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

        // Create a temporary stack to reverse the first k elements
        LinkedList<Integer> stack = new LinkedList<>();

        // Dequeue the first k elements and push them onto the stack
        for (int i = 0; i < k; i++) {
            stack.push(dequeue(queue));
        }

        // Enqueue the elements from the stack, effectively reversing them
        while (!stack.isEmpty()) {
            enqueue(queue, stack.pop());
        }

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