您好,登錄后才能下訂單哦!
這個方法用到了快指針和慢指針,他倆從頭結點一起跑,每次快指針走兩個節點,慢指針走一個節點,當進入環之后,快指針終會追上慢指針。這時,記錄相遇的節點,然后讓慢指針再跑一圈就可以測出環的長度了。
這個方法適用于任何情況,無論整個鏈表都是環,還是環的節點只有一個的。
#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 = NULL;
NODE* point1 = phead;
int num = 0;
int num1 = 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("鏈表中環的長度為: %d\n",num);
break;
}
}
while(1){ //當快慢指針在環中相遇時,一個新的指針從頭結點向后走,慢指針繼續走時,這兩個指針就會相遇在入環的節點中。(這個規律為什么會這樣,我也不知道,哪位大神知道,麻煩在評論區解釋一下。)
if(point1 == point)
break;
point1 = point1->next;
point = point->next;
num1++;
}
printf("此鏈表的長度為:%d\n",num1+num);
}
NODE* createlian(NODE* head)
{
NODE* poin = NULL;
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); //讓尾節點指向環開始的節點
printf("這個鏈表為:\n");
show(head);
return head;
}
int main(void)
{
NODE* head;
NODE* tail;
NODE* poin;
NODE* head1;
head = createlian(head);
check(head);
// show(head);
return 0;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。