LeetCode_Lined List CycleII

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

这道题让我很无语,感觉我的算法和AC的应该是一样的,但是就是TLE,贴出来:

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        ListNode* slow = head;
        ListNode* fast = head;
        do{
            if( !slow || !fast ) return NULL;
            slow = slow->next;
            fast = fast->next;
            if( fast ) fast = fast->next;
            else return NULL;
        }while( slow != fast );
        slow = head;
        while( slow != fast ){
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};
上面是AC的,下面是自己写的TLE:

/**
 * 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) {
        if (head==NULL)
        {
            return NULL;
        }

        ListNode *pSingleSpeed=head;
        ListNode *pDpubleSpeed=head;

        while (pSingleSpeed!=NULL&&pDpubleSpeed!=NULL)
        {
            pSingleSpeed=pSingleSpeed->next;
            pDpubleSpeed=pDpubleSpeed->next;
            if (pDpubleSpeed!=NULL)
            {
                pDpubleSpeed=pDpubleSpeed->next;
            }
            /*  else
            {
            return NULL;
            }*/
            if (pSingleSpeed==pDpubleSpeed/*&&pSingleSpeed!=NULL
                &&pDpubleSpeed!=NULL*/)
            {
                break;
            }
        }
       
        if (pDpubleSpeed==NULL||pSingleSpeed==NULL)
        {
            return NULL;
        }
        
        pDpubleSpeed=head;
        while (pDpubleSpeed!=pSingleSpeed)
        {
            pSingleSpeed=pDpubleSpeed->next;
            pSingleSpeed=pSingleSpeed->next;
        }
        return pSingleSpeed;
    }
};
两者思想都是一样的,先判断是否具有回路,如果有,让一个指针回到起点,两个指针以相同速度继续走,在此相遇地点就是环的入口,如果不清楚,画图一看就知道了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值