带环求环起开始节点位置

 1 bool hasLoop(linkedlist llist)
2 {
3 listnode *pf=llist;
4 listnode *ps=llist;
5
6 while(true)
7 {
8 if(pf && pf->next)
9 {
10 pf=pf->next->next;
11 }
12 else
13 return false;
14
15 ps=ps->next;
16
17 if(ps==pf)
18 {
19 //yes, there is a loop.
20 //if you just need to check if there is a loop, just return.
21 //but we need to extend it. So break to calc more.
22 break;
23 }
24 }
25
26 //calc the length of the circle.
27 int lengthX=0;
28 do{
29 ps=ps->next;
30 pf=pf->next->next;
31 lengthX++;
32 }while(ps!=pf)
33
34 //find the position of circle.
35 int lengthY=0;
36 linkedlistnode *p=llist;
37 while(p!=ps)
38 {
39 p=p->next;
40 ps=ps->next;
41 lengthY++;
42 }
43
44 printf("the length of circle is %d, the position of first elem in circle is %d.\n"lengthX, lengthY);
45
46 return true;
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值