Write a Java Program to Interleave the elements of two queues


The Java code demonstrates how to interleave the elements of two queues queue1 and queue2. The interleaving is done by alternately taking elements from each queue and adding them to a new queue resque.

  • Two queues of integers, queue1 and queue2, are created using the LinkedList implementation of the Queue interface.
  • Elements (integers) are added to both queue1 and queue2.
  • The content of both queues is printed using System.out.println() statements.
  • A new queue resque is created to store the interleaved elements.
  • A while loop runs as long as both queue1 and queue2 are not empty. In each iteration, it takes an element from queue1, removes it from the queue using remove(), and adds it to resque. Then, it takes an element from queue2, removes it from the queue, and adds it to resque. This alternately interleaves the elements from queue1 and queue2 into resque.
  • After the loop, there might be elements remaining in either queue1 or queue2. If queue1 is not empty, it dequeues its elements one by one and adds them to resque. Similarly, if queue2 is not empty, its elements are also dequeued and added to resque.
  • Finally, the content of the resque is printed, showing the interleaved queue.

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class QueueInterleave
{
	public static void main(String[] args)
	{
		Queue<Integer> queue1 = new LinkedList<>();
		Queue<Integer> queue2 = new LinkedList<>();
 
		// Adding elements to the queues
		queue1.add(1);
		queue1.add(2);
		queue1.add(3);
		queue1.add(4);
		queue1.add(5);
 
		queue2.add(6);
		queue2.add(7);
		queue2.add(8);
		queue2.add(9);
		queue2.add(10);
 
		System.out.println("First Queue Elements : "+queue1);
		System.out.println("Second Queue Elements : "+queue2);
 
		// Interleaving the elements of two queues
		Queue<Integer> resque = new LinkedList<>();
		while (!queue1.isEmpty() && !queue2.isEmpty())
		{
			resque.add(queue1.remove());
			resque.add(queue2.remove());
		}
 
		while (!queue1.isEmpty())
		{
			resque.add(queue1.remove());
		}
 
		while (!queue2.isEmpty())
		{
			resque.add(queue2.remove());
		}
 
		System.out.println("Interleaved Queue Elements :"+resque);
    }
}
 

Output

First Queue Elements : [1, 2, 3, 4, 5]
Second Queue Elements : [6, 7, 8, 9, 10]
Interleaved Queue Elements :[1, 6, 2, 7, 3, 8, 4, 9, 5, 10]

Example Programs