leetcode-142环形列表

641 阅读1分钟

取两个快慢指针,快指针速度为2,慢指针速度为1. 假设链表中有环,
计起点到相遇点距离为x, 相遇距环内相遇点的距离为y, 环内相遇距相遇点的距离为z, 如图所示:

image.png

相遇时: x + n*(y + z) + y = 2 * (x + y)
x = (n-1)(y+z) + z

当n=1时,x=z。在x的起点处和z的起点处同时前进,相遇点即为所求
当n>1时,x = (n-1)(y+1)。在x的起点出出发,将与在环内前进(n-1)(y+z)的点相遇

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        //n=1时
        ListNode* fastIndex = head;
        ListNode* slowIndex = head;
        while(fastIndex!=nullptr&&fastIndex->next!=nullptr){
            fastIndex = fastIndex->next->next;
            slowIndex = slowIndex->next; 
            if(fastIndex==slowIndex){
                slowIndex = head;
                while(fastIndex!=slowIndex){
                slowIndex = slowIndex->next;
                fastIndex = fastIndex->next;
                }
                return slowIndex;

            }
        }
        
        return nullptr;
    }
};