1. 程式人生 > >判斷單鏈表中是否存在迴環

判斷單鏈表中是否存在迴環

判斷單鏈表是否存在迴環原理很簡單,即假設有兩個指標p1,p2。在每次迴圈的時候,p1先走一步,p2走兩步,直到p2碰到空指標或兩者相等時迴圈結束,如果兩個指標相等則說明存在迴環。

具體程式碼如下:(僅供參考)

#include <iostream>
using namespace std;

#include <stdio.h>

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

Node *create()
{
	Node *head;
	int data=0;
	int i=0,j=0;
	Node *New;
	Node *q;
	head=(Node*)malloc(sizeof(Node));
	while(1)
	{
		cout<<"input the "<<(++i)<<"th "<<"data: ";
		cin>>data;
		
		if(data==0)
		{
			break;
		}

		New=(Node *)malloc(sizeof(Node));
		New->data=data;
	
		if(++j==1)
		{
			head->next=New;
		}
		else
		{
			q->next=New;
		}
		q=New;
	
	}
	New->next=NULL;
	return head;
}

int length(Node *head)
{
	Node *p;
	int len=0;

	p=head->next;
	if(head->next==NULL)
		return 0;
	while(p!=NULL)
	{
		len++;
		p=p->next;
	}
	return len;
}

void print(Node *head)
{
	Node *p=head ;
	int i=0;
	if(head->next==NULL)
		return ;

	while(p->next!=NULL)
	{	
		p=p->next;
		cout<<"The "<<++i<<"th data is: "<<p->data<<endl;
	
	}
	cout<<endl;

}

//判斷是否存在迴環
//如果存在,start存放回環開始節點
bool IsLoopList(Node *head,Node **start)
{
	Node *p1=head,*p2=head;
	if(head==NULL && head->next==NULL)
	{
		return false;
	}

	do
	{
		p1=p1->next;	//p1走一步
		p2=p2->next->next;//p2走兩步

	}while(p2 && p2->next && p1!=p2);

		if(p1==p2)
		{
			*start=p1;//p1為迴環開始節點
			return true;

		}
		else 
			return false;
}





int main()
{
	Node *head;
	head=create();
	print(head);
	cout<<"The length of List is: "<<length(head)<<endl;
	
	bool IsLoop=false;
	Node *start=head->next->next->next->next;//使第四個節點為迴環開始位置
	start->next=head->next;//迴環連線到第二個節點

	Node *loopStart=NULL;
	IsLoop=IsLoopList(head,&loopStart);
	cout<<"IsLoop="<<IsLoop<<endl;
	cout<<"IsbLoop==loopStart? "<<(loopStart==start)<<endl<<endl;

	return 0;

}


在上面主函式的情況下,手動設定了第四個節點為迴環的開始位置,並將迴環愛你接到第二個節點。最後的輸出均為1,表明存在迴環。

執行結果如下:


將主函式中

start->next=head->next;//迴環連線到第二個節點
註釋掉的話,,最後的輸出結果均為0,表明不存在迴環。輸出結果如下: