单链表判环

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

/*
* 链表判环
*/
#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\ncircle_start_point:%d\n",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\n",count);
    }else{
        printf("no circle in list\n");
    }
}

int main(){
    srand((unsigned)time(NULL));
    link head=GenerateList();
    judge(head);
    return 0;
}
posted @   fenicnn  阅读(325)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· 开发者新选择:用DeepSeek实现Cursor级智能编程的免费方案
· Tinyfox 发生重大改版
· 独立开发经验谈:如何通过 Docker 让潜在客户快速体验你的系统
· 小米CR6606,CR6608,CR6609 启用SSH和刷入OpenWRT 23.05.5
点击右上角即可分享
微信分享提示