leetcode - 142. Linked List Cycle II

在这里插入图片描述

/**
 * 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,*p2;
        bool f(0);
        if(head&&head->next)
        {
            p1=head->next;
            p2=head->next->next;
        }else{
            return NULL;
        }
        int i=1;
        while(p2&&p2->next)
        {
            if(p1==p2) 
            {
                f=1;
                break;
            }
            p1=p1->next;
            p2=p2->next->next;
            ++i;
        }
        if(!f) return NULL;
        p2=head;
        while(p1!=p2)
        {
            p1=p1->next;
            p2=p2->next;
        }
        return p1;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41938758/article/details/89094754