You have been given a singly Linked List of integers. Your task is to divide this list into two smaller singly-linked lists in which the nodes appear in alternating fashion from the original list.
For example:If the given linked list is 1 -> 2 -> 3 -> 4 -> 5 -> NULL
The first sub-list is 1 -> 3 -> 5 -> NULL.
The second sub-list is 2 -> 4 -> NULL.
If it is impossible to make any of the two smaller sub-lists, return an empty list i.e. NULL.
The first line of input contains an integer 'T' representing the number of test cases or queries to be processed. Then the test case follows.
The only line of each 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 each test case, print two lines representing the first and second linked lists respectively. The elements of each linked list must be separated by a single space and terminated by -1.
Print output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. just implement the function and return the answer.
1 <= T <= 10^2
0 <= LEN <= 5*10^3
1 <= data <= 10^9
Where LEN is the number of nodes in the Linked List.
Time Limit: 1 sec
2
1 2 3 4 5 -1
1 2 -1
1 3 5 -1
2 4 -1
1 -1
2 -1
For the first test case, we have 1, 3, 5 in the first and 2, 4 in the second linked list.
For the second test case, we have 1 in the first and 2 in the second linked list.
2
1 2 3 -1
1 -1
1 3 -1
2 -1
1 -1
-1
Append alternatively at the end of each linked list.
The idea is simple. We will maintain two tail pointers to the end of each linked list. When we will traverse in the original linked list, we alternatingly append the current node to the end of each list. For that, we will point the next of the tail node to the current node and move the tail pointer forward.
O(N), where N is the number of nodes in the linked list.
Here as we are traversing the list, for N nodes the time complexity will be linear hence the time complexity is O(N).
O(1)
we are not using any extra space.