LeetCode 141 - circular linked list I

Title Description
Given a list, the list is determined whether a ring.
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.
Example 1:
Input: head = [3,2,0, -4] , pos = 1
Output: true
explanation: the list has a ring tail portion connected to a second node.
Here Insert Picture Description
Example 2:
Input: head = [1,2], pos = 0
Output: true
explanation: the list has a ring, which is connected to the tail of the first node.
Here Insert Picture Description
Example 3:
Input: head = [1], pos = -1
Output: false
interpretation: the list does not ring.
Here Insert Picture Description

Solution: Freud's tortoise and hare

/**
 * 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) {
        ListNode *tortoise = head;
        ListNode *hare = head;
        while(hare!=NULL && hare->next!=NULL)
        {
            tortoise = tortoise->next;
            hare = hare->next->next;
            if(tortoise==hare) return true;
        } 
        return false;      
    }
};
Published 152 original articles · won praise 22 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_38204302/article/details/105103639