题目大意:判断链表中是否有环
分析:快慢指针相遇则有环
代码:
/**
* 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 && fast->next){
fast = fast->next->next;
slow = slow->next;
if(slow == fast) return true;
}
return false;
}
};
来源:CSDN
作者:tzyshiwolaogongya
链接:https://blog.csdn.net/tzyshiwolaogongya/article/details/104533092