#include <bits/stdc++.h>
using
namespace
std;
class
Node {
public
:
int
data;
Node* next;
};
void
splitList(Node* head, Node** head1_ref,
Node** head2_ref,
Node** head3_ref)
{
Node* slow_ptr = head;
Node* avg_ptr = head->next;
Node* fast_ptr = head->next->next;
if
(head == NULL
|| head->next == NULL
|| head->next->next == NULL)
return
;
while
(fast_ptr->next != head
&& fast_ptr->next->next != head) {
if
(fast_ptr->next->next->next
!= head)
fast_ptr
= fast_ptr->next->next->next;
else
{
fast_ptr = fast_ptr->next->next;
}
avg_ptr = avg_ptr->next->next;
slow_ptr = slow_ptr->next;
}
while
(fast_ptr->next != head)
fast_ptr = fast_ptr->next;
*head3_ref = avg_ptr->next;
fast_ptr->next = *head3_ref;
*head2_ref = slow_ptr->next;
avg_ptr->next = *head2_ref;
*head1_ref = head;
slow_ptr->next = *head1_ref;
}
void
push(Node** head_ref,
int
data)
{
Node* ptr1 =
new
Node();
Node* temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
if
(*head_ref != NULL) {
while
(temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1;
*head_ref = ptr1;
}
void
printList(Node* head)
{
Node* temp = head;
if
(head != NULL) {
do
{
cout << temp->data <<
" "
;
temp = temp->next;
}
while
(temp != head);
}
cout << endl;
}
int
main()
{
int
list_size, i;
Node* head = NULL;
Node* head1 = NULL;
Node* head2 = NULL;
Node* head3 = NULL;
push(&head, 1);
push(&head, 3);
push(&head, 5);
push(&head, 7);
push(&head, 9);
splitList(head, &head1, &head2, &head3);
printList(head1);
printList(head2);
printList(head3);
return
0;
}