Leetcode 142 Linked List Cycle II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010821666/article/details/82749518

Leetcode 142 Linked List Cycle II

struct ListNode
{
    int val;
    ListNode* next;
    ListNode(int x):val(x),next(NULL){}
};


class Solution {
public:
    ListNode *detectCycle(ListNode *head) {

        ListNode* fast = head;
        ListNode* slow = head;
        bool iscycle = false;
        while(fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
            if (fast == slow)
            {
                slow = head;
                while (fast != slow) {
                    slow = slow->next;
                    fast = fast->next;
                }
                return slow;

            }
        }
        return NULL;

    }
};

猜你喜欢

转载自blog.csdn.net/u010821666/article/details/82749518