判断链表时候有环,输出环的入口结点

版权声明: https://blog.csdn.net/if_i_were_a/article/details/82596651

//链表中环的入口结点
#include<stdio.h>
#include<malloc.h>
typedef struct node{
    int data;
    struct node *next;
}LinkNode; 
LinkNode* Creat_LinkList2()
{
    int x;
    int k=0;//计数 
    LinkNode* h;
    LinkNode *s,*t,*u;
    printf("请输入链表的数据域的值");
    scanf("%d",&x);
    h=(LinkNode *)malloc (sizeof(LinkNode));
    h->next=NULL;
    t=h;
    while(x!=-1) 
    {
        s=(LinkNode *)malloc(sizeof(LinkNode));
        s->data=x;
        s->next=t->next;
        t->next=s;
        t=s;
        if(k==5)
        u=t;
        k++; 
        scanf("%d",&x);
    }
    t->next=u;
    return h;

LinkNode * findNode(LinkNode * h)
{
    int k=1;
    //判断一个链表中是否有环
    LinkNode *p=h->next,*q=h->next;
    while(p->next)
    {
        p=p->next->next;
        q=q->next;
        if(p==q)
        break;
    }
    if(p!=q)
    {
        printf("这个链表是无环的节点");
        return;
    }
    //找到环之间隔了多少个位置 
    for(p=q->next;q!=p;p=p->next,k++); 
    //把速度快的指针放在放在合适的位置 
    for(q=h->next,p=h->next;k;p=p->next,k--);
    //找到交叉的节点 
    for(;q!=p;q=q->next,p=p->next);
    return q;
}
void printLinkList(LinkNode *h)
{
    LinkNode *p;
    for(p=h->next;p;p=p->next)
    printf("%d ",p->data);
}
int main(void)
{
    LinkNode *head,*y;
    head=Creat_LinkList2();
//    printLinkList(head); 
    y=findNode(head);
    printf("%d",y->data);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/if_i_were_a/article/details/82596651