Effectively check a loop in a list with linear cost
=============
1. Analysis
=============
typical case 1:
1->2->3->4->5->6->1
( loop in header, K = 0, N = 6)
typical case 2:
1->2->3->4->5->6->3
( loop in node 3, K = 2, N = 4)
Two pointers, one with each step 1, the other with each step 2
Suppose step = K + x ( or say cost)
K + x = 2*(K+x) - N
==>
x = N - k
=============
2. Algorithm
=============
typedef struct Node Node;
struct Node
{
void* data;
Node* p;
};
boolean check_loop(const Node* p)
{
Node* pTemp = p;
Node* p1 = p?(p->p):NULL;
Node* p2 = (p1)?(p1->p):NULL;
for(;p2;p1 = p1->p,p2 = (pTemp = (p2->p))?(pTemp->p):NULL )
{
if ( p1 == p2)
{
return true;
}
}
return false;
}
Check a loop in a list with line…
最新推荐文章于 2024-08-13 19:45:11 发布