/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*设置两个指针,一个一次走一步,一个一次走两步,如果两个指针最后相遇,那么链表有环。
如果走的快的指针最后变为空指针,则链表没有环。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast(head), *slow(head);
while(fast != nullptr && fast->next != nullptr){
fast = fast->next->next;
slow = slow->next;
if(slow == fast) return true;
}
return false;
}
};
LeetCode之Linked List Cycle
最新推荐文章于 2019-12-05 11:12:19 发布
