leetcode-142 Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

想法:(1)首先的判断链表中是否有环,若有环进行(2),没有环就返回NULL

         (2)参考https://www.cnblogs.com/jack204/archive/2011/09/14/2175559.html的分析,

          从链表头到环入口点等于(n-1)循环内环+相遇点到环入口点。于是可以从链表头和相遇点分别设一个 指针,每次各走一步,两个指针必定相遇,且相遇第一点为环入口点。此时返回其中一个指针即可。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(NULL == head || head->next == NULL)
            return NULL;
        bool cycle = false; 
        struct ListNode* fast = head;
        struct ListNode* slow = head;
        while(fast  && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast){
                
                cycle = true;
                break;
            }
        }
        if(cycle){
            slow = head;
            while(slow != fast){
                slow = slow->next;
                fast = fast->next;
            }
            return slow;
        }

        return NULL;
    }
};

猜你喜欢

转载自www.cnblogs.com/tingweichen/p/9882361.html