Leetcode question 141-circular linked list 1

Given a linked list, determine whether there is a ring in the linked list.

If there is a node in the linked list that can be reached again by continuously tracking the next pointer, then there is a ring in the linked list. In order to represent the rings in a given linked list, we use the integer pos to indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). If pos is -1, there are no rings in the linked list. Note: pos is not passed as a parameter, just to identify the actual situation of the linked list.

If there is a ring in the linked list, return true. Otherwise, it returns false.

Insert picture description here
Insert picture description here

Problem-solving ideas:
1. We create two pointers: fast pointer fast and slow pointer slow.
2. Let the slow pointer go one step at a time and the fast pointer two steps at a time.

slow = slow->next;
fast = fast->next->next;

3. If there is a ring, the fast pointer will catch up with the slow pointer.

Code

/**
 * 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) {
    
    
        //设置快慢指针slow,fast
        ListNode* slow = head,*fast = head;

        while(fast && fast->next)
        {
    
    
            slow = slow->next;//慢指针每次走一步
            fast = fast->next->next;//快指针每次走俩步

            if(fast == slow)
            {
    
    
                return true;
            }
        }

        return false;
        
    }
};

When you see this, some people may have questions, why can you catch up with the pointer two steps quickly? If you take 3 steps, 4 steps or n steps, can you catch up?
My answer is: 3 steps, 4 steps or n steps may catch up, but it may not catch up, and the cycle will continue.
Next, let us analyze a wave:
Insert picture description here
suppose that when the slow pointer enters the loop, the distance between fast and slow is x ,
and each time fast and slow go, the distance between them is reduced by one step.
It becomes x-1, x-2, x-3,... until x is reduced to 0 and meets.

If fast takes 3 steps, the distance x is
x-2, x-4,...
When x is an odd number, fast will skip slow and will not meet. After skipping, the gap is still odd, which will cause an endless loop.
It is similar to walking N steps, but also an endless loop.

Guess you like

Origin blog.csdn.net/weixin_50843868/article/details/111703821