給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。
爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
說明:不允許修改給定的鏈表。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:tail connects to node index 1
解釋:鏈表中有一個環,其尾部連接到第二個節點。
示例 2:
輸入:head = [1,2], pos = 0
輸出:tail connects to node index 0
解釋:鏈表中有一個環,其尾部連接到第一個節點。
示例 3:
輸入:head = [1], pos = -1
輸出:no cycle
解釋:鏈表中沒有環。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路: 整個過程爲,使用快慢指針,慢指針每輪走一個節點,快指針每輪走兩個節點,若存在環,快指針與慢指針必定相遇. 相遇後,快指針(或慢指針)回到鏈表頭節點,之後開始同時每次走一個節點,當慢指針與快指針再次相遇時,相遇點爲鏈表環的入口.
當然此方法可以判斷鏈表是否有環,當快慢指針第一次相遇即可說明有環.
判環代碼如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow=head;
ListNode *fast=head;
while(slow!=nullptr&&fast->next!=nullptr)
{
slow=slow->next;
fast=fast->next->next;
if(fast==nullptr)return false;
if(slow==fast)return true;
}
return false;
}
};
找到環的入口節點的原理證明如下:
代碼如下:
/**
* 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 *slow=head;
ListNode *fast=head;
while(slow!=nullptr&&fast->next!=nullptr)
{
slow=slow->next;
fast=fast->next->next;
if(fast==nullptr)return nullptr;
if(slow==fast)break;
}
if(slow==nullptr||fast->next==nullptr)return nullptr;
fast=head;
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
};