牛客NC4-判断链表中是否有环

题目描述

判断给定的链表中是否有环

扩展:

你能给出空间复杂度O(1)的解法么?

 

C++

1.空间复杂度O(n),利用哈希表,存在环即当前节点的next已经在哈希表中出现过

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <unordered_map>
class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_map<ListNode*, int> listmap;
        if(head == nullptr)
            return false;
        ListNode* pNow = head;
        while(pNow != nullptr){
            auto it = listmap.find(pNow);
            if(it != listmap.end()){//找到了,存在环
                return true;
            }
            else{
                listmap[pNow]++;
            }
            pNow = pNow->next;
        }
        return false;
    }
};

2.空间复杂度O(1),快慢指针,快指针每次走2步,慢指针每次走一步,如果存在环则运行一定次数后快慢指针会相等。不存在环,快指针会先指向nullptr。

/**
 * 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) {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast != nullptr && fast->next != nullptr ){//快指针每次走2步,慢指针每次走一步
            fast = fast->next->next;
            slow = slow->next;
            if(slow == fast)
                return true;
        }
        return false;
    }
};