思路分析:
快慢指针法:
定义两个指针( slow 和 fast ),同时设计一个循环让两个指针在循环中顺着链表移动。两个指针起点相同(都为head),但slow指针每次移动一格,fast指针每次移动两格。因为fast指针运动速度比slow指针快,若链表中无环,则slow指针始终追不上fast指针。若链表中有环,则fast指针会与slow指针在环上运动时相遇。
代码实现(c++):
/**
* 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)
{
if(head==nullptr) return 0;
ListNode* slow=head;
ListNode* fast=head;
while(fast->next!=nullptr&&fast->next->next!=nullptr)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
return 1;
}
return 0;
}
};
运行结果: