判断链表是否有环,返回环结点

前言

个人小记


一、代码如下

#include<stdio.h>
#include <stdlib.h>
#define MAX_LEN 20
#include <time.h>

typedef struct Node
{
    int data;
    struct Node* next;
}Node;

Node* init_node(int val)
{
    Node* node=(Node*)malloc(sizeof(Node));
    node->data=val;
    node->next=NULL;
    return node;
}

Node* insert(Node* head,int pos,int val)
{
    Node New_head;
    Node* p=&New_head;
    New_head.next=head;
    for(int i=0;i<pos;i++)p=p->next;
    Node* node=init_node(val);
    node->next=p->next;
    p->next=node;
    return New_head.next;
}

void clear(Node* head)
{
    if(head==NULL)return ;
    for(Node* p=head,*q;p;p=q)
    {
        q=p->next;
        free(p);
    }
    return ;
}

Node* loop(Node* head,int x)
{
    Node* p=head;
    for(int i=1;i<x;i++)p=p->next;
    Node* q=head;
    while(q->next)q=q->next;
    q->next=p;
    return head;
}

void print(Node* head)
{
    Node* p=head;
    while(p)
    {
        printf("%4d",p->data);
        p=p->next;
    }
    printf("\n");
    return ;
}

int n=1;
Node* findloop(Node* head)
{
    Node* p,*q;
    p=q=head;
    while(p&&p->next)
    {
        p=p->next->next;
        q=q->next;
        if(p==q)break;
    }
    if(p==NULL||p->next==NULL)
    {
        //printf("链表没有环\n");
        return NULL;
    }
    p=head;
    while(p!=q)
    {
        p=p->next;
        q=q->next;
        n++;
    }
    return p;
}

Node* unloop(Node* head)
{
    Node* p=findloop(head);
    if(p==NULL)
    {
        //printf("链表没有环\n");
        return head;
    }
    Node* q=p;
    while(q->next!=p)
    {
        q=q->next;
    }
    q->next=NULL;
    return head;
}

int main()
{
    srand((unsigned)time(0));
    Node *head=NULL;
    for(int i=0;i<MAX_LEN;i++)
    {
        head=insert(head,i,i+rand()%100);
    }
    print(head);
    if((rand()%100)%2) 
    {
        int x=rand()%(MAX_LEN-1)+1;
        printf("环的位置是%d\n",x);
        head=loop(head,x);
    }
    Node* node=findloop(head);
    if(node!=NULL)printf("结点的数值为:%d\n",node->data);
    else printf("此链表无环\n");
    
    head=unloop(head);
    clear(head);
    return 0;
}

二、结果如下

  90  99  93  45  63  34  98  41  89  43 105  60  21  98  61 109  59  98  54  27
环的位置是17
结点的数值为:59
sjq@SEER:~/coding$ ./a.out 
  83  82   5  49  39  50  33  48  70  61  82  96  64  59  27  31  54  79  25  32
环的位置是2
结点的数值为:82
sjq@SEER:~/coding$ ./a.out 
  40  26  82  68  70  66  86  31  97  74  34  72  89  37  53  46 106  78 116  28
此链表无环
  • 21
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值