Leetcode 142. Linked List Cycle II

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

思路:快慢指针的使用。首先,first为快指针,每次只走一步;second为慢指针,每次走两步;快慢指针同时开始遍历,当快慢指针相等时,说明有环。并且,假设链表开始到环起点长为 s,环长为 l;当second走到begin时,first走到了s%l的位置,相对于环上;first于second相距为l-s%l,当first于second在环上相遇时,second走到了l-s%l的距离,因为每次可以拉近一个距离;这时third开始从头遍历,first于third相遇时,third走过s,first走过s%l,相对于环,first到了l-s%l+s%l,也就是l的地方,既begin;这就是环的起始点。

class Solution {
public:
    ListNode *detectCycle(ListNode *head) 
    {
       ListNode* fhead=new ListNode(1);
       if(head==NULL) return NULL;
       fhead->next=head;
       ListNode * h1=fhead;
       ListNode * h2=fhead;
       do
       {
           if(h1->next!=NULL&&h1->next->next!=NULL)
           {
               h1=h1->next->next;
           }
           else
           {
               return NULL;
           }
           h2=h2->next;
       }
       while(h1!=h2);
       ListNode* h3=fhead;
       do
       {
           h1=h1->next;
           h3=h3->next;
       }
       while(h1!=h3);
       return h3;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值