# 单向链表当中的环路判别问题

p1走的路径： p+c ＝ n；         c为p1和p2相交点，距离环路入口的距离

p2走的路径： p+c+k*L = 2*N；   L为环路的周长，k是整数

#include "iostream.h"
#include "memory.h"
#include "new.h"
class CList {
public:
int nData;
CList * pNext;
} * pRoot = NULL;

const int size = sizeof(CList) / sizeof(int);
int  buffer[101*size];
bool Init(int n)
{
pRoot = (CList*)buffer;
if ( n<1 && n>98 )  return false;
CList * pTemp = NULL;
for ( int i=0; i<101; i++ ) {
pTemp = new (buffer+i*size) CList();
pTemp->nData = i;
pTemp->pNext = (CList *)(buffer + (i+1)*size);
};
pTemp->pNext = (CList *) (buffer + n*size);
return true;
}

void ClearCircle(CList * pRoot)
{
CList * p1, * p2;
p1 = p2 = pRoot;
do {
p2 = p2->pNext->pNext;
p1 = p1->pNext;
} while ( p2!=NULL && p1!=p2);
if ( p1 == p2 ) {
p2 = pRoot;
while (1) {
p2 = p2->pNext;
if ( p1->pNext == p2 ) break;
p1 = p1->pNext;
}
p1->pNext = NULL;
}
}

main()
{
CList * pList = pRoot;
if (Init(21) )
{
cout << "Before clear:!" << "/r/n";
pList = pRoot;
for ( int i=0; i<104; i++)
{
cout << pList->nData << "/r/n";
pList = pList->pNext;
}
ClearCircle(pRoot);
}
cout << "After clear:" << "/r/n";
pList = pRoot;
while (pList) {
cout << pList->nData << "/r/n";
pList = pList->pNext;
}
return 0;
}