每日一题(9) - 判断单链表是否有环

本文介绍了一种用于检测链表中是否存在环形结构的算法。通过快慢指针的移动策略,该算法能够在链表中高效地查找环形节点,从而判断链表是否具有环形结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来自剑指Offer

题目


分析


代码

bool IsCycle(ListNode* pHead)
{
	assert(pHead != NULL);
	ListNode* pFast = pHead;
	ListNode* pSlow = pHead;
	while (pFast->m_pNext && pFast->m_pNext->m_pNext)
	{
		pFast = pFast->m_pNext->m_pNext;
		pSlow = pSlow->m_pNext;
		if (pFast == pSlow)
		{
			return true;
		}
	}
	return false;
}

测试代码

#include <iostream>
#include <assert.h>
using namespace std;

struct ListNode
{
	int m_Data;
	ListNode* m_pNext;
};


bool IsCycle(ListNode* pHead)
{
	assert(pHead != NULL);
	ListNode* pFast = pHead;
	ListNode* pSlow = pHead;
	while (pFast->m_pNext && pFast->m_pNext->m_pNext)
	{
		pFast = pFast->m_pNext->m_pNext;
		pSlow = pSlow->m_pNext;
		if (pFast == pSlow)
		{
			return true;
		}
	}
	return false;
}

void CreateList(ListNode** pHead,int nLen)//头指针使用指针的指针
{
	assert(*pHead == NULL && nLen > 0);
	ListNode* pCur = NULL;
	ListNode* pNewNode = NULL;
	for (int i = 0;i < nLen;i++)
	{
		pNewNode = new ListNode;
		cin>>pNewNode->m_Data;
		pNewNode->m_pNext = NULL;

		if (*pHead == NULL)
		{
			*pHead = pNewNode;
			pCur = *pHead;
		}
		else
		{
			pCur->m_pNext = pNewNode;
			pCur = pNewNode;
		}
	}
}

/*把链表最后一个结点指向第三个结点*/
void CreateCycle(ListNode* pHead)
{
	assert(pHead);
	ListNode* pLastNode = pHead;
	while (pLastNode->m_pNext)
	{
		pLastNode = pLastNode->m_pNext;
	}
	if (pHead->m_pNext && pHead->m_pNext->m_pNext)
	{
		pLastNode->m_pNext =  pHead->m_pNext->m_pNext;
	}
}


int main()
{
	int nLen = 0;
	bool bIsCircle = false;
	ListNode* pHead = NULL;
	ListNode* pHeadSec = NULL;
	ListNode* pMidNode = NULL;

	cout<<"please input node num: ";
	cin >> nLen;
	CreateList(&pHead,nLen);//注意传参使用引用
	CreateCycle(pHead);
	bIsCircle = IsCycle(pHead);
	if (bIsCircle)
	{
		cout<<"有环!"<<endl;
	}
	else
	{
		cout<<"无环"<<endl;
	}

	cout<<"please input node num: ";
	cin >> nLen;
	CreateList(&pHeadSec,nLen);//注意传参使用引用
	bIsCircle = IsCycle(pHeadSec);
	if (bIsCircle)
	{
		cout<<"有环!"<<endl;
	}
	else
	{
		cout<<"无环"<<endl;
	}
	
	system("pause");
	return 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值