#include<iostream>
using namespace std;

typedef struct node
{
	int data;  
	struct node *next;
}Node;

Node *createList(int n)
{
	Node *p = new Node[n];
	for( int i = 1; i < n; ++i)
	{
		p[i - 1].next = &p[i];
		p[i - 1].data = i;
	}
	p[n - 1].next = NULL;
	p[n - 1].data = n;
	return p;
}

Node *createListWithRing(int n)
{
	Node *p = new Node[n];
	for( int i = 1; i < n; ++i)
	{
		p[i - 1].next = &p[i];
		p[i - 1].data = i;
	}
	p[n - 1].next = &p[n/2];
	p[n - 1].data = n;
	return p;
}

//pFast相当于摩托车,pSlow相当于自行车
//摩托车在前,自行车在后,如果还能相遇,则必然有环
bool listHasRing(Node *p)
{
	Node *pSlow = &p[0];
	Node *pFast = &p[1];
	while(NULL != pSlow && NULL != pFast -> next) // 经网友提醒,在使用p->next之前一定要检查p, 下面类似。感谢网友。
	{
		if(pSlow == pFast)
			return true;
		pSlow = pSlow -> next;
		pFast = pFast -> next ->next;
	}
	return false;
}

void print(bool b)
{
	if(b)
		cout << "There is a ring in the list." << endl;
	else
		cout << "There is no ring in the list." << endl;
}

int main()
{
	int n = 10;
	Node *head = createList(n);
	print(listHasRing(head));
	delete [] head; 

	head = createListWithRing(10);
	print(listHasRing(head));
	delete [] head; 
	return 0;
}


 


本文转载:CSDN博客