码迷,mamicode.com
首页 > 其他好文 > 详细

判断单链表是否有环

时间:2014-05-09 14:12:54      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:style   tar   ext   c   int   art   

判断单链表是否有环
假设两个指针分别为p1和p2,每循环一次只向前走一步,p2向前走两步,知道p2碰到NULL指针或者两个指针相等则说明有环
如果存在,start存放在圆环开始的节点
bool IsLoop(node *head,node *start)
{
node *p1=head,*p2=head;
if(head==NULL||head->next==NULL);//head为NULl或者链表为空
{
return false;
}
do
{
p1=p1->next;
p2=p2->next->next;//p2走两步 
}while(p2&&p2->next&&p1!=p2)
if(p1==p2)
{
*start=p1;//p1为圆环开始点
return true;
}
else
{
return false;
}
}
int main()
{
bool bLoop=false;
node *head=create();//create()函数的使用见我的博客(数据结构->单链表的创建)
node *start=head->next->next;
start->next=head->next;
node *loopstart=NULL;
bLoop=IsLoop(head,&loopstart);
printf("bloop=%d\n",bloop);
printf("bloop==loopstart?%d\n",(loopstart==start));
return 0;
}

判断单链表是否有环,布布扣,bubuko.com

判断单链表是否有环

标签:style   tar   ext   c   int   art   

原文地址:http://blog.csdn.net/u012388338/article/details/25375947

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!