跳转至

141.环形链表 (Easy)*

题目描述*

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例*

输入:head = [3,2,0,-4], pos = 1

输出:true

输入:head = [1], pos = -1

输出:false

进阶*

使用 O(1) 内存解决问题?

代码*

快慢指针。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr || head->next == nullptr) {
            return false;
        }
        ListNode *slow = head, *fast = head;
        while(fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast) {
                return true;
            }
        }
        return false;
    }
};

最后更新: July 23, 2022