单链表中是否有环

#include<iostream>
using namespace std;

struct ListNode{
	int m;
	ListNode *next;
};

ListNode *Creat ()
{
	ListNode *pHead = nullptr;
	ListNode *p1,*p2;
	p1 = new ListNode;
	cout<<"Please Enter a Number:"<<endl;
	cin>>p1->m;
	while(p1->m != 0)
	{
		if(pHead == nullptr)
		{
			pHead = p1;
			p2 = p1;
		}
		else 
		{
			p2->next = p1;
			p2 = p1;
		}
		p1 = new ListNode;
		cout<<"Please Enter a Number:"<<endl;
		cin>>p1->m;
	}
	p2->next = nullptr;
	return pHead;
}

void print(ListNode *pHead)
{
	ListNode *p = pHead;
	while(p != nullptr)
	{
		cout<< p->m<< "\t";
		p = p->next;
	}
	cout<<endl;
}

bool Hascircle(ListNode *Head)
{
	ListNode *pfast = Head;
	ListNode *pslow = Head;
	while(pfast!=nullptr && pfast->next!=nullptr)
	{
		pfast = pfast->next->next;
		pslow = pslow->next;
		if (pfast == pslow)
			return true;
	}
	return false;
}

int main ()
{
	ListNode *Head;
	Head = Creat();
	cout<<"The ListNode is"<<endl;
	print(Head);
	bool h;
	h = Hascircle(Head);
	if(h == true)  
		cout<<"Have a circle."<<endl;
	else
		cout<<"Have no circle."<<endl;
}

猜你喜欢

转载自blog.csdn.net/hannah_aimee/article/details/60878811
今日推荐