zoukankan      html  css  js  c++  java
  • 单链表判环

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

    /*
    * 链表判环
    */
    #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;
    }
  • 相关阅读:
    Socket网络编程--简单Web服务器(4)
    GCC学习笔记
    字符分隔符'1'(u0001)的困惑
    g++编译时遇到问题undefined reference to
    ROS学习笔记(三)
    cJSON笔记
    ROS学习笔记(二)
    ROS学习笔记(一)
    ffmpeg推流方式采用TCP协议
    Android OS的image文件组成
  • 原文地址:https://www.cnblogs.com/fenice/p/8699973.html
Copyright © 2011-2022 走看看