题目来源:https://leetcode.cn/problems/linked-list-cycle/description/
C++题解:声明两个一快一慢的索引,快的每次走两步,慢的每次走一步,如果快慢能相遇,则说明有环。注意fast每次走两步,需要判断fast和fast->next是否为空来决定是否到链表尾部。
/**
* 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* slow = head,* fast = head;
bool flg = false;
if(head == NULL) return flg;
if(head->next == NULL) return flg;
while(fast&&fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast==slow){
flg = true;
break;
}
}
return flg;
}
};