Leetcode 142 Solution

This article provides solution to leetcode question 142 (linked-list-cycle-ii)

https://leetcode.com/problems/linked-list-cycle-ii

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* p1 = head;
        ListNode* p2 = head;
        ListNode* p3 = NULL;

        while (p1 && p2)
        {
            if (p3 == NULL)
            {
                p1 = p1->next;
                p2 = p2->next;

                if (p2 == NULL)
                    return NULL;

                p2 = p2->next;

                if (p1 == p2)
                {
                    p3 = head;
                    continue;
                }
            }
            else
            {
                if (p1 == p3)
                    return p1;

                p1 = p1->next;
                p3 = p3->next;
            }
        }

        return NULL;
    }
};