Segregate Odd-Even
There is a wedding ceremony at NinjaLand. The bride and groom want everybody to play a game and thus, they have blindfolded the attendees. The people from the bride’s side are holding odd numbers and people from the groom’s side are holding the even numbers. For the game to start quickly, all the bride’s side people should come first, followed by the groom’s side people in the same order.
The attendees of the wedding with their numbers are given in the form of a Singly Linked List, arranged randomly.
A singly linked list is a type of linked list that is unidirectional; that is, it can be traversed in only one direction from head to the last node (tail).
Example:
The attendees holding numbers from 1, 4, 3 are shown:
As the organizers are busy, you have to arrange all the people by arranging the bride’s side people first followed by the groom’s side people sequentially.
Note:
For the above example 1 -> 4 -> 3, 1 -> 3 -> 4 is the only correct answer, i.e nodes should be grouped sequentially. Hence, 3 -> 1 -> 4 is the wrong answer as we have to preserve the same order.
Input Format
The first line of input contains an integer T, the number of test cases. Then each test case follows.
The first and the only line of every test case contains the elements of the singly linked list separated by a single space and terminated by -1.
Hence, -1 would never be a list element.
Output Format:
For every test case, print the bride’s side attendees followed by the groom’s side attendees.
The attendees/elements should be single-space separated, terminated by -1.
The output of each test case is printed in a separate line.
Note :
You don't need to print the output, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 5 * 10^4
0 <= data <= 10^4 and data != -1
Where 'N' denotes the number of elements in the Singly Linked List and 'data' represents the value of those elements.
Time Limit: 1 sec
CodingNinjas
author
2y
Iterative Approach 1
As we have to arrange the nodes such that all the odd nodes should come before all the even nodes, we can move all the even valued nodes from their current positions to the end of ...read more
CodingNinjas
author
2y
Iterative Approach 2
The idea is to split the linked list into two: one containing all odd valued nodes and others containing all the even valued nodes. And finally, attach the even node linked list af...read more
Help your peers!
Add answer anonymously...
Top Wipro Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app