LeetCode:Linked List Cycle II

本文介绍了一种高效的方法来确定链表中环的起始节点。通过使用快慢指针技巧,可以在O(n)时间内找到环的入口,而不需要额外的空间。首先利用快慢指针判断链表是否存在环,若存在则重新定位慢指针到头节点并同步前进,当两指针再次相遇时即为环的起始位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

思路:第一次按照Linked List Cycle的解法去做,果断超时。最后参考了网上的思路如下:

(1)定义slow和fast指针,都指向head结点,然后slow指针每次向后走1个结点,fast指针每次向后走2个结点。

(2)如果fast指针为空,则说明不存在环;如果fast指针和slow指针相等,则说明存在环。

(3)存在环时将slow指针指向head结点,然后slow指针和fast指针每次都向后走一个结点。

(4)如果slow指针和fast指针相等,该处结点就是环的开始结点,返回slow指针。

 

本文参考了:http://blog.youkuaiyun.com/cs_guoxiaozhu/article/details/14209743

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *detectCycle(ListNode *head) {
12         if(head==NULL||head->next==NULL)
13                 return NULL;
14         ListNode *slow=head,*fast=head;
15             while(fast!=NULL)
16             {
17                 slow=slow->next;
18                 fast=fast->next;
19                 if(fast!=NULL)
20                     fast=fast->next;
21                 if(slow==fast)
22                 {
23                     slow=head;
24                     while(slow!=fast)
25                     {
26                         slow=slow->next;
27                         fast=fast->next;
28                     }
29                     return slow;
30                 }
31             }
32             return NULL;
33     }
34 };

 

转载于:https://www.cnblogs.com/levicode/p/3978094.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值