leetcode 141 环形链表

这篇博客介绍了两种检测链表中是否存在环的方法:一种是利用unordered_set存储节点,当遇到重复节点时返回true;另一种是采用快慢指针,一个速度为2,一个速度为1,如果相遇则存在环。博主提供了详细的代码实现,并给出了数学证明。

1.我想到的用set。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode*> us;
        while(head!=NULL){
            if(us.find(head)==us.end())
                us.insert(head);
            else
                return true;
            head=head->next;
        }
        return false;
    }
};
2. 双指针,不使用额外空间。

一个速度为2,一个速度为1。

https://blog.youkuaiyun.com/nomasp/article/details/51598735

作者没给出证明。我的证明如下:

node == n

car = (2i+1) //%n

man= i //%n

Q:car-man==k*n ?

=>

i+1 evenly divide n

yes

车速度为2,人速度为1.

如果有环,他们离得最近的时候可能相遇,如果不,那么相差1.

设车、人坐标为……

Q:坐标之差可能为环的整数倍吗?

可以,i+1可以==n

代码思路:

车前进2,人前进1.

if 坐标相等,true

if car==NULL || car->next ==NULL , false

不判断人,因为车比人快,已经判断过了。

还有,同一行定义两个指针:

ListNode *i , *j ; 

### 关于LeetCode 142题(环形链表II)的C++解决方案 对于检测并返回链表中环起始节点的问题,可以采用快慢指针的方法。当两个指针相遇时,说明存在环;此时再通过特定操作找到环的入口。 #### 方法概述 定义两个指针`slow`和`fast`,均指向链表头部。`slow`每次移动一步而`fast`则每次前进两步。如果二者最终能在某一时刻重合,则表明此链表确实含有循环结构[^2]。 一旦确认有环之后,为了定位入环的第一个结点: - 将其中一个指针重新移回起点; - 另一指针保持当前位置不变; - 接下来让这两个指针对应地都按照单步速度向前遍历直到它们再次碰面——这时所处的位置即为我们要找的那个特殊节点。 下面是具体的代码实现方式: ```cpp class Solution { public: ListNode *detectCycle(ListNode *head) { if (!head || !head->next) return nullptr; ListNode* slow = head; ListNode* fast = head; while (fast != NULL && fast->next != NULL){ slow = slow->next; // Move one step at a time. fast = fast->next->next; // Move two steps at once. if(slow == fast){ // Cycle detected. break; } } if(fast == NULL || fast->next == NULL){ return NULL; // No cycle found. }else{ slow = head; // Reset 'slow' to the start of list. while(slow != fast){ // Both pointers move forward by single node each iteration till they meet again which will be entry point of loop. slow = slow -> next; fast = fast -> next; } return slow; // Return either as both are pointing same now i.e., entrance of circle. } } }; ``` 上述算法不仅能够有效地识别是否存在闭环现象,而且还能精确定位到形成闭包的具体位置所在之处[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大富大贵7

很高兴能够帮助到你 感谢打赏

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

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

打赏作者

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

抵扣说明:

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

余额充值