判断单链表是否成环形

题目描述:判断一个单向链表是否形成环形结构;

思路分析:定义一个快慢指针,快指针一次走两步,慢指针一次走一步,如果链表有环,则一定可以相遇。

代码实现:

#include<iostream>
using namespace std;

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

bool Insert_tail(Node **list,int value)//尾插
{
	Node *node = new Node;
	node -> data = value;
	node ->next = NULL;
	if(*list == NULL)
	{
		*list = node;
		return true;
	}
	Node *p = *list;
	for(;p->next !=NULL;p=p->next );
	p->next = node;
	return true;
}

Node *FindValue(Node *list,int value)
{
	if(list == NULL)
	{
		return NULL;
	}
	Node *p = list;
	for(;p!=NULL;p=p->next )
	{
		if(p->data == value)
		{
			return p;
		}
	}
	return NULL;
}

bool IsRing(Node *list)//是否成环
{
	if(list == NULL)
	{
		return false;
	}
	Node *fast = list;
	Node *last = list;
	while(1)
	{
		fast = fast->next; //fast先走一步
		if(fast == NULL)//有空指针,则证明一定不成环形
		{
			return false;
		}
		else if(fast == last) //如果快慢指针相遇,则证明有环
		{
			return true;
		}
		fast = fast->next ;//fast再走一步
		last = last ->next ;//last走一步
	}
}

void clear(Node **list)//清除
{
	Node *p = *list;
	for(;p!=NULL;p=p->next )
	{
			Node *q = p -> next;
			p->next = q->next;
			delete q;
	}
	delete p;
}

void Show(Node *list)//打印函数
{
	if(list == NULL)
		return;
	Node *p = list;
	for(;p != NULL;p = p->next)
	{
		cout<<p->data<<" ";
	}
	cout<<endl;
}

int main()
{
	Node *head1 = NULL;
	Node *head2 = NULL;
	int arr[] = {1,2,3,4,5};
	int lenarr = sizeof(arr)/sizeof(arr[0]);
	for(int i=0;i<lenarr;++i)
	{
		Insert_tail(&head1,arr[i]); //尾插
		Insert_tail(&head2,arr[i]); //尾插
	}
	Show(head1);
	Show(head2);
	Node *p =FindValue(head1,2);
	Node *q = FindValue(head1,5);
	q->next = p;
	cout<<IsRing(head1)<<endl;
	cout<<IsRing(head2)<<endl;
}
总结:快慢指针的思想要掌握哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值