您的位置:首页 > 其它

求单链表环的入口结点 Linked List Cycle II

2013-11-22 21:21 309 查看
    对于单链表,有的没有环,最后一个结点指向NULL,从头遍历到NULL就结束了。而有的是存在环,那么遍历时会在环内死循环,没有结尾。

本题目源自于leetcode。经典题目。

题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.solve it without using extra space.

思路:

    slow指针每次走1步,fast指针每次走2步。如果链表有环,那么两个指针一定会相遇。



    设链表头到环入口结点的结点数目是a,环内的结点数目r。假设相遇时,fast指针已经绕环转了n圈,比slow多走了n*r步。假设环的入口结点到相遇结点的结点数目为x。
    那么在相遇时,slow走了a+x步,fast走了a+x+n*r步。
    由于fast的步调是slow的两倍,所以有a+x = n*r。因而,a = n*r - x
显然,从相遇位置开始,走n*r - x步,一定可以到达环的入口结点;从链表头开始,走a步,也会到达环的入口。并且我们得到了a = n*r - x。所以我们让两个指针,一个从相遇位置出发一个从链表头出发,让他们都单步前进。因为a = n*r - x,所以他们一定会在环的入口相遇。

具体做法:

    第一次遍历用slow指针和fast指针遍历,相遇时,记下相遇位置。

    第二次遍历p1指针从链表头出发,p2指针从上次的相遇位置出发,p1p2相遇时所在的位置就是环的入口。

代码:

/**
* 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 *fast, *slow;
fast = slow = head;
while(fast->next != NULL && fast->next->next!= NULL)
{
slow = slow->next;
fast = fast->next->next;
if(fast == slow) //slow和fast相遇
break;
}
if(fast->next == NULL || fast->next->next == NULL)
return NULL;

slow = head; //slow从链表头开始,fast从刚才的相遇位置开始。它们会在环的入口相遇。
while(slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: