Divide Linked List In Two
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.
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.
Input format :
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.
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
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.