Posted on

Description

Submission

/**
 * 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) {
        ListNode *ptr1, *ptr2;
        if(head) ptr1 = head;
        else return false;
        if(head->next) ptr2 = head->next;
        else return false;
        for( ; ptr1 && ptr2; )  {
            if(ptr1 == ptr2) return true;
            if(ptr1->next) ptr1 = ptr1->next;
            else return false;
            if(ptr2->next && ptr2->next->next) ptr2 = ptr2->next->next;
            else return false;
        } 
        return false;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *