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.
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.
Example 3:
Input: head = [1], pos = -1
Output: false
interpretation: the list does not ring.
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;
}
};