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.
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.
1 6 2 7 3 8 4 9 5 10
Video Contributed by Parul Shandilya
- Interleave the first half of the queue with second half
- Check if a queue can be sorted into another queue using a stack
- Stack and Queue in Python using queue Module
- queue::front() and queue::back() in C++ STL
- queue::push() and queue::pop() in C++ STL
- queue::swap() in C++ STL
- queue::emplace() in C++ STL
- Queue using Stacks
- Reversing a Queue
- Priority Queue in Python
- Reversing a queue using recursion
- Priority Queue | Set 1 (Introduction)
- Reverse a path in BST using queue
- Reversing the first K elements of a Queue
- Applications of Priority Queue
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : ParulShandilya