題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle-ii
給定一個(gè)鏈表,返回鏈表開始入環(huán)的第一個(gè)節(jié)點(diǎn)。 如果鏈表無環(huán),則返回 null。
為了表示給定鏈表中的環(huán),我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環(huán)。
說明:不允許修改給定的鏈表。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:tail connects to node index 1
解釋:鏈表中有一個(gè)環(huán),其尾部連接到第二個(gè)節(jié)點(diǎn)。

image.png
示例 2:
輸入:head = [1,2], pos = 0
輸出:tail connects to node index 0
解釋:鏈表中有一個(gè)環(huán),其尾部連接到第一個(gè)節(jié)點(diǎn)。

image.png
示例 3:
輸入:head = [1], pos = -1
輸出:no cycle
解釋:鏈表中沒有環(huán)。

image.png
解法一,用哈希表:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
ListNode cur = head;
while(cur != null){
if (set.contains(cur)){
return cur;
}
set.add(cur);
cur = cur.next;
}
return null;
}
}
進(jìn)階:
你是否可以不用額外空間解決此題?
在上一題快慢指針解法上修改一下,先得到快慢指針相遇的節(jié)點(diǎn),再找到環(huán)的長度len,最后再從頭結(jié)點(diǎn)依次嘗試,每次走len步,如果回到了原點(diǎn),即答案。代碼如下:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null)
return null;
ListNode slow = head;
ListNode quick = head.next;
while(slow != null){
if(slow == quick){
break;
}
slow = slow.next;
if(quick == null || quick.next == null){
return null;
}
quick = quick.next.next;
}
//此時(shí)slow節(jié)點(diǎn)就是兩指針相遇的節(jié)點(diǎn),再在這個(gè)節(jié)點(diǎn)往下走,計(jì)算出環(huán)的長度
quick = quick.next;
int len = 1;
while(slow != quick){
quick = quick.next;
len++;
}
//得到了環(huán)的長度,再從頭結(jié)點(diǎn),每次走len步,如果回到了當(dāng)前節(jié)點(diǎn),說明這個(gè)節(jié)點(diǎn)就是環(huán)的起點(diǎn)
ListNode tmpNode = head;
while(true){
quick = tmpNode;
slow = quick;
int tmp = len;
while(tmp != 0){
quick = quick.next;
tmp--;
}
if(quick == slow){
return quick;
}
tmpNode = tmpNode.next;
}
}
}
注:官方題解中有優(yōu)化版,在找到相遇點(diǎn)之后尋找入環(huán)點(diǎn)的部分可以遵循特定公式,詳情請(qǐng)見官方題解。
https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode/