Split a Circular Linked List into two halves

Given a Cirular Linked List of size N, split it into two halves circular lists. If there are odd number of nodes in the given circular linked list then out of the resulting two halved lists, first list should have one node more than the second list. The resultant lists should also be circular lists and not linear lists.


Example 1:

Input:

Circular LinkedList: 1->5->7

Output:

1 5

7

 

Example 2:

Input:

Circular LinkedList: 2->6->1->5

Output:

2 6

1 5

 

c++ implementation:

void splitList(Node *head, Node **head1_ref, 

                           Node **head2_ref)  

{  

    Node *slow = head;  

    Node *fast = head;  

      

    if(head == NULL)  

        return;  

  

    while(fast->next != head &&  

          fast->next->next != head)  

    {  

        fast = fast->next->next;  

        slow = slow->next;  

    }  

    

    if(fast->next->next == head)

      fast = fast->next;

   

     Node *re = slow->next; 

   

    *head1_ref=head;

    slow->next=head;

    

    *head2_ref=re;

    fast->next=re;   

    

Time Complexity: O(n)  
darkmode