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.
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); } }
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]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions