/*有环链表寻找入口节点
1、求环长度:快慢指针,一个指针走一步,一个走两步,当两个指针第一次相遇的时候,走的次数即是环长度
2、一个指针先走环的长度步数,另外一个指针从头开始, 然后两个指针同时走,第一次相遇即是环的入口节点*/
single_list_node* find_cricle_list_entrance(single_list_node* head)
{
single_list_node* p1 = head, *p2 = head;
int circle_len = 0, n = 0, len_entrance = 0;
if(NULL == head)
{
return head;
}
while( NULL != p1 && NULL != p2)
{
p1 = p1->next;
p2 = p2->next;
++circle_len;
if(NULL != p2)
{
p2 = p2->next;
}
if(p1 == p2)
{
break;
}
}
if(NULL == p2 || NULL == p1)
{
printf("the list has not cricle.\n\n");
return NULL;
}
p1 = head;
p2 = head;
n = 0;
while(n < circle_len)
{
p1 = p1->next;
++n;
}
while(1)
{
if(p1 == p2)
{
break;
}
p1 = p1->next;
p2 = p2->next;
++len_entrance;
}
printf("circle_length = %d, list len = %d\n", circle_len, (circle_len+ len_entrance));
return p2;
}
测试用例:
//环的尾部节点指向链表中间节点
tmp = Find_middle_node(ls2);
printf("ls2's middle node is %d\n\n", tmp->data);
tail = find_single_linked_tail(ls2);
tail->next = tmp;
printf("tail node data = %d\n", tail->data);
// SingleList_showdata_sleep(ls2);
tmp2 = find_cricle_list_entrance(ls2);
printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
//无环链表
tail->next = NULL;
tmp2 = find_cricle_list_entrance(ls2);
//一个节点成环
tail->next = tail;
tmp2 = find_cricle_list_entrance(ls2);
printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
//整个链表是一个大环
tail->next = ls2;
tmp2 = find_cricle_list_entrance(ls2);
printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
//一个节点的链表,无环
ls3 = CreateSingleList(2);
tmp2 = find_cricle_list_entrance(ls3);
//一个节点的链表,有环
ls3->next = ls3;
tmp2 = find_cricle_list_entrance(ls3);
printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
ls3->next = NULL;
ls3 = SingleList_insertHead(ls3,33);
printf("ls3:\n");
SingleList_showdata(ls3);
//ls3 有两个节点,无环
tmp2 = find_cricle_list_entrance(ls3);
ls3->next->next = ls3->next;
//两个节点,尾部节点自成环
tmp2 = find_cricle_list_entrance(ls3);
printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
ls3->next->next = ls3;
tmp2 = find_cricle_list_entrance(ls3);
printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);