力扣第142题 环形链表 II

力扣第142题 环形链表 II

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    public:
    ListNode *getMeet(ListNode *head)
    {
        if (head == NULL || head->next == NULL)
        {
            return NULL;
        }
        ListNode * stepOne = head;
        ListNode * stepTwo = head->next;
        while (stepOne != stepTwo)
        {
            if (stepTwo == NULL || stepTwo->next == NULL)
            {
                return NULL;
            }
            stepOne = stepOne->next;
            stepTwo = stepTwo->next->next;
        }
        return stepOne;
    }

    ListNode *detectCycle(ListNode *head) 
    {
        if (head == NULL)
        {
            return NULL;
        }
        ListNode *meetNode = getMeet(head);
        if (meetNode == NULL)
        {
            return NULL;
        }
        ListNode *step1 = head;
        ListNode *step2 = meetNode->next;
        while (step1 != step2)
        {
            step1 = step1->next;
            step2 = step2->next;
        }
        return step1;
    }

};

posted on 2020-03-06 20:10  woodjay  阅读(117)  评论(0编辑  收藏  举报

导航