Write a Java program to Move all Even elements to the front of the queue while maintaining the relative order of other elements
The Java code defines a class MoveEvenToFront with a method moveEvenToFront that moves all even elements to the front of a given Queue of integers while maintaining the original order of the odd elements.
- The moveEvenToFront method takes a Queue<Integer> named queue as input and moves all even elements to the front.
- It creates a temporary Queue<Integer> named tempQueue to store the even elements.
- It also calculates the initial size of the queue using the size() method.
- The method uses a loop to iterate size times to process each element in the queue.
- In each iteration, the element is dequeued from the front of the queue using poll() and stored in the variable element.
- The method checks if element is even (i.e., its remainder when divided by 2 is 0). If element is even, it is enqueued into the tempQueue using offer(). Otherwise, if element is odd, it is enqueued back into the original queue using offer().
- After the loop finishes, all even elements will be moved to the front of the original queue, and odd elements will be at the back.
- The method then dequeues elements from the tempQueue and enqueues them back into the original queue, effectively moving the even elements to the front.
- In the main method, a Queue<Integer> named queue is created 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 moveEvenToFront method is then called with the queue as an argument, and even elements are moved to the front of the queue.
- Finally, the queue after moving even elements to the front is printed using System.out.println().
Source Code
import java.util.*;
public class MoveEvenToFront
{
public static void moveEvenToFront(Queue<Integer> queue)
{
int size = queue.size();
Queue<Integer> tempQueue = new LinkedList<>();
for (int i = 0; i < size; i++)
{
int element = queue.poll();
if (element % 2 == 0)
{
tempQueue.offer(element);
}
else
{
queue.offer(element);
}
}
while (!tempQueue.isEmpty())
{
queue.offer(tempQueue.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);
System.out.println("Original Queue : " + queue);
moveEvenToFront(queue);
System.out.println("Queue after moving even elements to the front: " + queue);
}
}
Output
Original Queue : [1, 2, 3, 4, 5]
Queue after moving even elements to the front: [1, 3, 5, 2, 4]