【leetcode】141. Linked List Cycle

本文介绍了一种使用快慢指针技巧高效检测链表是否存在循环的方法。通过实例详细解析了算法原理,展示了如何利用两个速度不同的指针判断链表中是否出现小循环。

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

题目描述:

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

 

题目看起来不是很复杂,属于一般的链表问题。即给一个链表判断它是否内部存在小循环,pos在所写的成员函数中并没有写出,只给出链表,实际上pos代表的意义是开始发生循环的在链表的位置,只是为了描述问题的方便,毕竟循环链表没办法表示,所以可以忽略,只要有所给的链表进行判断即可,不必考虑。

考虑使用快指针和慢指针的双指针的方法, 即一个指针每次走一步,跳到next上,而另一个指针每次走两步,跳到next->next上,这样当有循环时,两个指针迟早会指向一个node结点上,即两个指针相同(指针的地址相同),快指针可以走3步甚至多步都可以,我们采用2步的方法;当没有循环时快指针,或者快指针的next会探测到链表的终点NULL(c++中用大写的NULL来表示),这样即可解决问题。

这个方法非常巧妙,100%的速度,代码为:

/**
 * 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) {
        if(!head || !head->next)
            return false;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while(slow != fast)
        {
            if(!fast || !fast->next)
            {
                return false;
            }
            slow = slow->next;
            fast = fast->next->next;
        }
        return true;
    }
};

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值