Split a Circular Linked List into three halves of almost same size
Split given Circular Linked List into three halves without calculating its length such that the difference between a linked list with a maximum number of nodes and a linked list with a minimum number of nodes is minimum.
Input: Circular Linked List: 1->3->5->7->9
Output: 1 3
Input: Circular Linked List: 2->4->8
Approach: The approach to solving this problem is using the tortoise and hare algorithm.
- Move the slow, avg, and fast pointers by 1, 2 and 3
- When the fast pointer reached NULL, avg pointer reached the end of the second halves and the slow pointer reached the end of the first halves.
- Make the Third half circular.
- Make the second half circular.
- Make the first half circular.
- Set head pointers of the two linked list
Below is the implementation of the above approach:
9 7 5 3 1
Time Complexity: O(N)
Auxiliary Space: O(1)