leetcode || 142、Linked List Cycle II

problem:

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?

Hide Tags
  Linked List Two Pointers
题意:如果一个单链表存在环形结构,返回环的起点。空间复杂度满足O(1)

thinking:

(1)上一题使用快慢指针可以判断是否存在环形结构,当fast==slow时,他俩指向的结点是环形结点的任意一个,与环的大小和位置有关。

(2)改造如下:慢指针和快指针都从头节点开始,慢指针每次走一步,快指针每次走两步,当slow==fast时,fast不变,slow回到起点head处,

此时快慢指针每次都走一步,再次相等时,两指针指向的节点即为环形的起点,也为终点。

举例证明: 1->2->3->2, 3指向前一个节点2

当快慢指针第一次相遇时,同时指向3,将慢指针重置到1,每次前进一步,再次相遇时,两个指针同时指向2,即为环形起点

(3)细节:快慢指针都从head开始,起点要一致。

code:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
       if(head==NULL)
           return head;
       ListNode *slow=head;
       ListNode *fast=head;
       while(fast->next!=NULL && fast->next->next!=NULL)
       {
           slow=slow->next;
           fast=fast->next->next;
           if(slow==fast)
           {
               slow=head;
               while(slow!=fast)
               {
                   slow=slow->next;
                   fast=fast->next;
               }
               return slow;
           } 
       }
       return NULL;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值