[LeetCode] Linked List Cycle

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

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

带环链表的检测,使用快慢指针判断,快指针每次走两步,慢指针每次走一步,如果快慢指针相遇,则链表有环,否则快指针会一直走到nullptr为止退出循环,返回false。

在有环的情况下,最终快慢指针一定都走在环内。

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

在无环情况下,时间复杂度为O(n / 2) 

在有环情况下,最坏情况下O(n)最好情况下O(n / 2)

总的时间复杂度O(n)

还可以使用map来存储出现的节点,如果一个链表有环,则遍历链表时必然有节点会遍历2次。利用map中出现第二次的元素可以判断出该链表有环。

这需要O(n)的空间复杂度

/**
 * 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_map<ListNode*, int> m;
        while (head != nullptr) {
            if (m.count(head)) {
                return true;
            }
            else {
                m[head]++;
            }
            head = head->next;
        }
        return false;
    }
};
// 13 ms
原文地址:https://www.cnblogs.com/immjc/p/7634422.html