Pages

Thursday, October 16, 2025

Interleave two halves of a Queue(even Length) in Java

 import java.util.*;


public class Main

{

    public static void interLeave(Queue<Integer> q) {

        Queue<Integer> firstHalf = new LinkedList<>();

        int size = q.size(); // size must be constant, or there will be anomaly.

        

        

        for(int i=0; i<size/2;i++) {

            

            firstHalf.add(q.remove());

            

        }

        

        

        while(!firstHalf.isEmpty()) {

            q.add(firstHalf.remove());

            q.add(q.remove());

        }

    }

    

public static void main(String[] args) {

        Queue<Integer> q = new LinkedList<>();

        q.add(1);

        q.add(2);

        q.add(3);

        q.add(4);

        q.add(5);

        q.add(6);

        q.add(7);

        q.add(8);

        q.add(9);

        q.add(10);

        

        interLeave(q);

        // print Q

        while(!q.isEmpty()) {

            System.out.print(q.remove() + " ");

        }

}

}

No comments:

Post a Comment

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...