142-环形链表II
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
Example 1
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
Example 2
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
Example 3
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。
思路
这道题一开始就没有思路,后来看了下题目评论中的想法,这道题还是有点考智商的。。。
首先双指针来判断是否有环,有环的话,快指针从头开始单步走,当再次遇到慢指针时,所指结点就是开始入环的第一个结点。
这里有两点要注意:
快指针所走的速度是慢指针的2倍,当快指针开始单步走时,再次相遇的结点就是入环的第一个结点
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
if(head == NULL || head->next == NULL) return NULL;
struct ListNode *fast = head;
struct ListNode *slow = head;
int isPrime=0;
while(fast && slow && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if(fast == slow)
{
isPrime = 1;
fast = head;
while(fast != slow)
{
fast = fast->next;
slow = slow->next;
}
return slow;
break;
}
}
return NULL;
}