leetcode 环形链表 简单

 

 

 快慢指针:慢指针每次走一步,快指针每次走两步,如果有环则会出现两指针相遇

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head) return false;
        ListNode* quick = head -> next;
        while(quick && head && quick != head) {
            head = head -> next;
            quick = quick -> next;
            if(quick) quick = quick -> next;
        }
        return quick == head;
    }
};

 

posted @ 2021-07-23 23:43  rookie_Acmer  阅读(33)  评论(0)    收藏  举报