LeetCode 141. Linked List Cycle 有环链表

1.题目

给定一个链表,确定它是否有一个环。

 

2.思路

“双指针”解决问题   快慢指针 fast slow 
fast 指针每次走两步  slow 指针每次走一步
如果走得快的指针和走得慢的指针“相遇”了,那么链表就有环。

3.实现

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr)
            return false;
        
        ListNode* slow = head;
        ListNode* fast = head;
        
        while(fast != nullptr && fast->next != nullptr)
        {
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast)
                return true;
        }
        
        return false; //走到链表结尾处
        
        
    }
};

猜你喜欢

转载自blog.csdn.net/u014128608/article/details/92843048