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;
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;
1489

被折叠的 条评论
为什么被折叠?



