代码如下:
class Solution {
public:
bool hasCycle(ListNode *head)
{
if(head == nullptr || head -> next == nullptr)
return false;
ListNode *fast , *slow;
slow = head;
fast = head -> next;
while(fast != slow)
{
if(fast == nullptr || fast -> next == nullptr)
return false;
slow = slow -> next;
fast = fast -> next -> next;
}
return true;
}
};
设置两个指针一个指针每次指向下一个位置,另一个指针指向下下个位置,如果链表中存在环,则两个指针一定会相等,否则则不会相等