Ring linked list is simple

first level title

secondary title

The circular linked list gives you a head node head of the linked list to 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 cycle in the linked list. In order to represent the ring in the given linked list, the evaluation system internally uses the integer pos
to indicate the position where the tail of the linked list is connected to the linked list (the index starts from 0). Note: pos is not passed as a parameter. Just to identify the actual situation of the linked list.

Returns true if there is a cycle in the linked list. Otherwise, returns false.

Example 1:

Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a ring in the linked list whose tail is connected to the second node. Example 2:

Input: head = [1,2], pos = 0 Output: true Explanation: There is a ring in the linked list whose tail is connected to the first node. Example 3:

Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.

Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnwzei/

bool hasCycle(ListNode *head) {
    
    
        if(!head)
            return false;
        ListNode *slow=head;
        ListNode *fast=head->next;
        while(slow!=fast)
        {
    
    
            if(fast==NULL||fast->next==NULL)
                return false;
            slow=slow->next;
            fast=fast->next->next;
        }
        return true;
    }

Freud's circle method written before

Guess you like

Origin blog.csdn.net/BeiWoFW/article/details/124415617