单链表判环

判断单链表是否有环,可以通过设置一个慢指针和一个快指针,每次慢指针走一步,快指针就走两步,如果两个点相遇,就说明单链表有环。

/*
* 链表判环
*/
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<cstdio>
using namespace std;
typedef struct node* link;
typedef struct node{
    int value;
    link next;
}Node;

link GenerateList(){
    int n=rand()%100+1;
    int random_position=rand()%n+1;
    printf("node_number:%d
circle_start_point:%d
",n,random_position);
    link head=NULL,random_address=NULL;
    link current_address=NULL;
    for(int i=1;i<=n;i++){
        link p=new Node();
        p->value=rand();
        p->next=NULL;
        if(i==1){
            head=current_address=p;
        }else{
            current_address->next=p;
            current_address=p;
        }
        if(i==random_position){
            random_address=p;
        }
    }
    current_address->next=random_address;
    return head;
}

void judge(link head){
    link p1,p2;
    p1=p2=head;

    //判断是否存在环
    int circle_exist=0;
    while(p1!=NULL&&p2!=NULL){
        p2=p2->next;
        if(p2==p1){
            circle_exist=1; break;
        }
        if(p2==NULL) break;
        p2=p2->next;
        if(p2==p1){
            circle_exist=1; break;
        }
        p1=p1->next;
    }
    if(circle_exist){
        int count=0;
        //统计环大小
        if(p2->next!=p2){
            count++; p2=p2->next;
            while(p2!=p1){
                p2=p2->next;
                count++;
            }
        }
        printf("circle round:%d
",count);
    }else{
        printf("no circle in list
");
    }
}

int main(){
    srand((unsigned)time(NULL));
    link head=GenerateList();
    judge(head);
    return 0;
}
原文地址:https://www.cnblogs.com/fenice/p/8699973.html