Write a Java program to Reverse the first half of the elements and leave the second half unchanged


The Java code defines a class ReverseFirstHalf with a method reverseFirstHalf that reverses the first half of a given Queue of integers.

  • The reverseFirstHalf method takes a Queue<Integer> named queue as input and reverses the first half of the elements in the queue.
  • It calculates the size of the queue using the size() method and then determines the halfsize by dividing the size by 2.
  • The method uses a Stack<Integer> named stack to temporarily store the first half of the elements in the queue in reverse order.
  • It iterates from index 0 to halfsize - 1 and for each iteration, it removes an element from the front of the queue using poll() and pushes it onto the stack using push().
  • After the stack has stored the first half of the elements in reverse order, the method dequeues elements from the stack and enqueues them back into the queue using pop() and offer().
  • At this point, the first half of the elements in the queue have been reversed.
  • To restore the original order of the queue, the method dequeues halfsize elements from the front of the queue and enqueues them back into the queue using poll() and offer().
  • The main method creates a Queue<Integer> named queue using the LinkedList implementation of the Queue interface. Elements (integers) are added to the queue using the offer() method.
  • The original queue is printed using System.out.println().
  • The reverseFirstHalf method is then called with the queue as an argument, and the first half of the queue is reversed.
  • Finally, the queue after reversing the first half is printed using System.out.println().

Source Code

import java.util.*;
public class ReverseFirstHalf
{
	public static void reverseFirstHalf(Queue<Integer> queue)
	{
		int size = queue.size();
		int halfsize = size / 2;
 
		Stack<Integer> stack = new Stack<>();
		for (int i = 0; i < halfsize; i++)
		{
			stack.push(queue.poll());
		}
 
		while (!stack.isEmpty())
		{
			queue.offer(stack.pop());
		}
 
		for (int i = 0; i < halfsize; i++)
		{
			queue.offer(queue.poll());
		}
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(1);
		queue.offer(2);
		queue.offer(3);
		queue.offer(4);
		queue.offer(5);
		queue.offer(6);
 
		System.out.println("Original Queue : " + queue);
		reverseFirstHalf(queue);
		System.out.println("Queue after reversing first half : " + queue);
	}
}

Output

Original Queue : [1, 2, 3, 4, 5, 6]
Queue after reversing first half : [3, 2, 1, 4, 5, 6]

Example Programs