Reverse the first “K” elements of a queue

mail@pastecode.io avatar
unknown
java
6 months ago
927 B
0
Indexable
Never
/*

    Time complexity: O(N + K)
    Space complexity: O(N)

    where 'N' is the size of the queue 
	and 'K' is the number of elements to be reversed.

*/

import java.util.Queue;
import java.util.Stack;

public class Solution {
	public static void reverse(Queue<Integer> queue, int k) {
		// If queue is empty or if k exceeds the size of the queue.
		if (queue.isEmpty() || k > queue.size()) {
			return;
		}

		if (k <= 0) {
			return;
		}

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

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

		while (!stack.isEmpty()) {
			queue.add(stack.peek());
			stack.pop();
		}

		// Remove the remaining elements and enqueue them at the end of the Queue.
		for (int i = 0; i < queue.size() - k; i++) {

			queue.add(queue.peek());
			queue.remove();
		}
	}

}
Leave a Comment