LeetCode 141. 环形链表 (快慢指针)

环形链表

/**
 * 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) {
    
    
        bool flag = false;
        ListNode *fast = head, *slow = head;
        while(fast && slow){
    
    
        // 防止在起点的时候判断相遇
            if(fast == slow && flag) return true;
            slow = slow->next;
            if(!fast->next) return false;
            else fast = fast->next->next;
            flag = true;
        }
        return false; 
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44846324/article/details/108970938