Skip to content
Related Articles

Related Articles

Interleave the first half of the queue with second half
  • Difficulty Level : Medium
  • Last Updated : 18 Sep, 2018

Given a queue of integers of even length, rearrange the elements by interleaving the first half of the queue with the second half of the queue. We are allowed to use only the queue data structure.

Examples:

Input :  1 2 3 4
Output : 1 3 2 4

Input : 11 12 13 14 15 16 17 18 19 20
Output : 11 16 12 17 13 18 14 19 15 20

Create two auxiliary queues q1 and q2. Insert first half in one queue q1 and another half in another queue q2. Now insert elements back to given queue by picking them from q1 and q2 alternatively.




// CPP program to interleave queue elements
// using only queue data structure.
#include <bits/stdc++.h>
using namespace std;
  
void interleave(queue<int> &q)
{
    queue<int> q1, q2;
  
    int n = q.size();
  
    // Insert first half in q1
    for (int i = 0; i < n / 2; i++) {
        q1.push(q.front());
        q.pop();
    }
  
    // insert second half in q2
    for (int i = 0; i < n / 2; i++) {
        q2.push(q.front());
        q.pop();
    }
     
    // Insert elements of q1 and q2 back
    // to q in alternate order.
    for (int i = 0; i < n/2; i++) {
        q.push(q1.front());
        q1.pop();
        q.push(q2.front());
        q2.pop();
    }
}
  
// Driver code
int main()
{
    // Creating an example queue with 10
    // elements.
    queue<int> q;
    for (int i = 1; i <= 10; i++) 
        q.push(i);  
  
    interleave(q);
  
    // Printing queue elements
    int n = q.size();
    for (int i = 0; i < n; i++) {
        cout << q.front() << " ";
        q.pop();
    }
}


Output:

1 6 2 7 3 8 4 9 5 10

Video Contributed by Parul Shandilya

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :