Circular linked list 2

Leecode brush title

  • Title Description

Given a list, return the first node into the beginning of the chain ring. If chain acyclic, null is returned.
To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.
Description: Do not allow to modify the given list.

  • Examples

Input: head = [3,2,0, -4] , pos = 1
Output: tail connects to node index 1
explained: the list has a ring tail portion connected to a second node.
Here Insert Picture Description

  • Thinking
    Here Insert Picture Description

As shown, the use of fast and slow pointer pointer, and start from scratch node. Fast take two steps each predetermined pointer, each pointer slow step, the S (fast pointer) = 2 * S (slow pointer), S represents a distance.
D is assumed that eventually meet, and therefore the following relationship is obtained:
AB + + BCDEB the BD = 2 * (the BD + AB) ------ (. 1)
==> the BD + AB = BCDEB ----- (2 )
according to the relationship of the circle: BD + DB = BCDEB ----- ( 3)
in (2), (3) can be obtained, AB = DB ----- (4)
Therefore, when the programming may be recording speed node pointers meet, and then again from the start node, when the two nodes shall meet cycle start node.

  • Code
/**
 * 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) 
    {
        ListNode* fast=head;
        ListNode* slow=head;
        bool cycle=false;
        while(fast&&fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow)
            {
                cycle=true;
                break;
            }
        }
        if(cycle)
        {
            ListNode* s=head;
            while(s!=slow)
            {
                s=s->next;
                slow=slow->next;
            }
            return s;
        }
        return NULL;
    }
};

Guess you like

Origin blog.csdn.net/qq_42780025/article/details/90766678