給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 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
解釋 鏈表中沒有環。
進階:
你是否可以不用額外空間解決此題?
C++1
首先確定是否存在環,如果存在則記錄快指針和慢指針重合節點的指針a,再從頭結點開始遍歷鏈表,遍歷指針記爲b。每次指針b和a都向下個節點移動一步,等到再次相遇時就是尾節點連到鏈表上的節點位置;如果環不存在環則返回NULL
。
/**
* 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, *temp;
int pos = -1;
while(fast&&fast->next){
fast = fast->next->next;
slow = slow->next;
temp = fast;
if(fast == slow){
while(head!=temp){
head = head->next;
temp = temp->next;
}
return head;
}
}
return NULL;
}
};