Leetcode 142: Linked List Cycle II

55 阅读1分钟

先做/铺垫: Leedcode 141

官方链接 解题思路:

  1. 按linked list本身性质解题
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        set<ListNode*> nodes;
        ListNode* node = head;
        while(node!= nullptr){
            if(nodes.find(node) != nodes.end()){
                return node;
            } 
            nodes.insert(node);
            node = node->next;
        }
        return nullptr;
    }
};

2.快慢指针

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;

        while( fast != nullptr && fast->next != nullptr){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow) {
                ListNode* index = head;
                while(index != slow){
                    index= index->next;
                    slow=slow->next;
                }
                return index;
            }
        } 
        return nullptr;
    }
};

第二个快慢指针写了很久: 错误原因:

  1. 细节: fast = fast->next;写成了 fast = head->next; 写代码纠错的能力偏差
  2. fast != nullptr && fast->next != nullptr 写反了。这个细节也要注意。c++是很敏感的,写的时候一定要注意细节。