判断一个链表中是否有环

如何判断一个链表中是否存在环:

设置两个指针,开始都指向链表头,然后其中一个指针每次向前走一步,另一个指针每次向前走两步,如果快的遇到NULL了,证明该链表中没有环,如果有环,快的指针每次都要比慢的多走一步,最终两个指针会相遇,(注意:这里快指针不会跳过慢指针而不相遇,因为它每次都只比慢指针多走一个单位)

 

// CPlus1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <list>
#include <string>
#include <iostream>
using namespace std;

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

// If cicular exist or not in the list.
bool circular(Node* list)
{
   if(list == NULL)
   {
	   return false;
   }

   Node* pFast = list;
   Node* pSlow = list;

   while(pFast->next != NULL && pFast->next->next!=NULL)
   {
	   pFast = pFast->next;
	   pSlow = pSlow->next->next;

	   if(pFast == pSlow)
	   {
		   return true;
	   }
   }

   return false;
}

int _tmain(int argc, _TCHAR* argv[])
{	
	Node s1,s2,s3,s4,s5;
	s1.data = 0;
	s2.data = 1;
	s3.data = 2;
	s4.data = 3;
	s5.data = 4;
	s5.next = &s3;
	s4.next = &s5;
	s3.next = &s4;
	s2.next = &s3;
	s1.next = &s2;
	Node *p = &s1;
	bool found = circular(p);
	if(found)
	{
		printf("true");
	}
	else
	{
		printf("false");
	}

	return 0;
}




 

你可能感兴趣的:(判断一个链表中是否有环)