判断一个链表中是否存在环

问题:判断一个链表中是否存在环

思路:快慢指针实现,设置两个指针一个p1,p2,p1每次移动一步,p2每次移动两步,若p2能够到达NULL节点,则无环,若p2追上p1指针,则有环。

#include <iostream>
#include<malloc.h>

using namespace std;

typedef struct node{
 int num;
 struct node *next;
}Node,*PNode;

void searchNode(PNode Head)
{
    if(Head==NULL)
        return;

    PNode pd=Head;
    while(pd!=NULL)
    {
        cout<<pd->num<<endl;
        pd=pd->next;
    }
}

//删除链表中某一节点
bool judge_circle(PNode Head)
{
    PNode p1,p2;
    p1=p2=Head;
    while(p2!=NULL)
    {
        p2=p2->next->next;
        p1=p1->next;
        if(p2==p1)
            return true;
    }
    return false;
}

int main()
{
    PNode item;
    Node d={1,NULL};
    Node c={2,&d};
    Node b={3,&c};
    Node a={4,&b};
    d.next=&b;
    item=&a;
    //searchNode(item);
    cout<<judge_circle(item)<<endl;
    //delete_node(&c,2);
    //searchNode(item);
    return 0;
}

输出结果:1

猜你喜欢

转载自blog.csdn.net/u013069552/article/details/81139200