Niuke Classic Linked List Question—(NC4) Determine whether there is a ring in the linked list

Full difficulty factor * * * * *, the difficulty factor of this question * *.
Frequent enthusiasm for full exams, enthusiasm * * * * *for this question * * * * *.

1. Title description

Insert picture description here

2. Topic link

  1. Cattle off topic Link Is there a ring to determine the list

3. Problem analysis

  1. One possibility is that the linked list has no ring, and it will go to nullptr when traversing.
  2. Another situation is that the linked list has a ring, and the nullptr will not be reached during traversal. A fast pointer and a slow pointer are defined. 当fast和slow进环以6就会围着环同时运动,且fast比slow每次多走一步。直到fast和slow相遇.
  • fast every time you go 两步, that is fast=fast->next->next;
  • Every time slow goes 一步, that is slow=slow->next;

3.1 Analysis icon

Insert picture description here

3.2 Detailed explanation of icons

  1. Fast and slow are initially head.
  2. In case one, if there is no loop, fast will definitely go to nullptr.
  3. In case two, if there is a ring, when fast and slow enter the ring at the same time, they will move around the ring at the same time, and fast takes one step more than slow. It becomes a chasing problem until fast and slow meet.

4. Problem-solving 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) {
    
    
        //注释1
        if(head == NULL)
        {
    
    
            return false;
        }
        //注释2
        struct ListNode *fast = head;
        struct ListNode *slow = head;
        //注释3
        while(fast && fast->next)
        {
    
    
            fast = fast ->next ->next;
            slow = slow ->next;
            if(fast == slow)
            {
    
    
                return true;
            }
        }
        return false;
    }
};

5. Detailed explanation of code comments

  1. Note 1: The head pointer is nullified first. So as not to cause null pointer access.
  2. Note 2: Define fast and slow pointers and point to head at the same time.
  3. Note 3: The list is traversed while(fast && fast->next)in fast->next判空order to avoid the while loop = FAST fast ->next-> Next cause null pointer access.

1.如有错误或者没能理解的地方,请及时评论或者私信,及时修改更新
2.会持续更新相关链表高频题目,分类专栏—数据结构

Guess you like

Origin blog.csdn.net/weixin_45313447/article/details/115266576