判断单链表中是否存在回环

判断单链表是否存在回环原理很简单,即假设有两个指针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,表明不存在回环。输出结果如下:









  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C-Jonn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值