首页 > 代码库 > 计算一个单项链表(链表中有环)中环的长度
计算一个单项链表(链表中有环)中环的长度
这个方法用到了快指针和慢指针,他俩从头结点一起跑,每次快指针走两个节点,慢指针走一个节点,当进入环之后,快指针终会追上慢指针。这时,记录相遇的节点,然后让慢指针再跑一圈就可以测出环的长度了。
这个方法适用于任何情况,无论整个链表都是环,还是环的节点只有一个的。
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int num;
struct node* next;
}NODE;
NODE* create(NODE* phead,int nu)
{
NODE* tmp = malloc(sizeof(struct node));
tmp->num = nu;
NODE* find = phead;
if(phead == NULL){
return tmp;
}
else{
while(find->next != NULL)
find = find->next;
find->next = tmp;
return phead;
}
}
void show(NODE* phead)
{
int i=0;
while(i<25){
printf("%d ",phead->num);
phead = phead->next;
i++;
}
printf("\n");
#if 0
while(phead){
printf("%d ",phead->num);
phead = phead->next;
}
printf("\n");
#endif
}
void createring(NODE* phead, NODE* point)
{
while(phead->next != NULL)
phead = phead->next;
phead->next = point;
}
NODE* point(NODE* phead)
{
while(phead->next != NULL)
phead = phead->next;
return phead;
}
void check(NODE* phead)
{
NODE* quick = phead;
NODE* slow = phead;
NODE* point;
int num = 0;
while(1){
quick = quick->next->next; //快指针一次走两个
slow = slow->next; //慢指针一次走一个
if(slow == quick){
point = slow;
point = point->next; //记录当两个指针相遇时的位置,从这个位置开始计数,当指针转一圈时结束
num++;
while(slow != point){
point = point->next;
num++;
}
printf("the ring long is: %d\n",num);
break;
}
}
}
int main(void)
{
NODE* head;
NODE* tail;
NODE* poin;
NODE* head1;
head = create(head,21);
create(head,22);
create(head,23);
create(head,24);
create(head,25);
create(head,26);
poin = point(head); //记录从环开始的节点
create(head,27);
create(head,28);
create(head,29);
create(head,30);
create(head,31);
create(head,32);
create(head,33);
createring(head,poin); //让尾节点指向环开始的节点
check(head);
// show(head);
return 0;
}
计算一个单项链表(链表中有环)中环的长度