問題描述:
給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。
爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
說明:不允許修改給定的鏈表。
問題分析:
本題在前一題的基礎上,增加了關於位置的定義,除了採用雙指針可以找到環之外,還需要使用快慢雙指針確定環起點。
/**
* 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) {
ListNode *fast = head, *slow = head;
//第一次快慢指針相遇
while(fast!=nullptr&&fast->next!=nullptr)
{
fast = fast->next->next;
slow = slow->next;
if(fast==slow) //表示相遇了
{
fast = head; //讓快指針從頭再來
while(fast!=slow)
{
fast = fast->next;
slow = slow->next;
}
return fast;
break;
}
}
return nullptr; //如果不是環
}
};