141. Linked List Cycle

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;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容