给定一个链表,判断链表中是否有环。
/**
* 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* fast = head;
ListNode* slow = head;
//设置快慢指针,慢指针一次走一步,快指针一次走两步,如果有环的话快慢指针总会相等。
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
};
---------------------------------------------------------Vivi 2020-4-4-------------------------