leetcode hot100刷题日记——26.环形链表

leetcode hot100刷题日记——26.环形链表_第1张图片
解答:(快慢指针,他俩在环里肯定会有相遇的时候)

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

时间复杂度:O(N)
空间复杂度:O(1)

你可能感兴趣的:(力扣刷题专栏,leetcode,链表,算法)