Linked List Cycle

本文介绍了一种通过双指针法判断单链表中是否存在循环的方法,并提供了相应的C++代码实现。此方法利用快慢指针,当快指针追上慢指针时,表明链表存在环。

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

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

判断一个单链表里是否有循环,这个问题以前在一本书上见过,具体思路是这样的:

定义两个节点,都从头开始,一个每次走两步,另一个每次走一步,如果有循环,那么这两个节点肯定会相遇。

具体代码如下:

#include <iostream>
#include <vector>
using namespace std;


struct ListNode {
     int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)return false;
ListNode *tmpFast = head;
ListNode *tmpSlow = head;
do 
{
if(tmpFast!=NULL)
tmpFast = tmpFast->next;
if(tmpFast!=NULL)
tmpFast = tmpFast->next;
if(tmpFast==NULL)
return false;
tmpSlow = tmpSlow->next;
} while (tmpFast != tmpSlow);
return true;
}
};


void main()
{
ListNode *a = new ListNode(3);
a->next = a;
/*a->next = new ListNode(2);
a->next->next = new ListNode(0);
a->next->next->next = new ListNode(-4);
a->next->next->next->next = a->next;*/
Solution s;
bool cycle = s.hasCycle(a);
while(1);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值