141. Linked List Cycle

141. Linked List Cycle_第1张图片
image.png

用一快一慢两个指针,如果慢的能追的上快的,就说明有环,如果有一个到了NULL,说明没有环。只要有换,绝不可能出现next为NULL的情况。

/**
 * 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) {
        if(head == NULL){
            return false;
        }
        ListNode * slow = head;
        ListNode * fast = head->next;
        while(slow && fast){
            if(slow == fast){
                return true;
            }
            slow = slow->next;
            if(fast->next == NULL){
                return false;
                
            }
            fast = fast->next->next;
            
        }
        return false;
    }
};

你可能感兴趣的:(141. Linked List Cycle)