Leetcode142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
判断是否有环,如果有那需要找到环的入口点
解法一 哈希表
public ListNode detectCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<>();
while (head != null) {
set.add(head);
head = head.next;
if (set.contains(head)) {
return head;
}
}
return null;
}
解法二 快慢指针
设两指针 fast,slow 指向链表头部 head,fast 每轮走 2 步,slow 每轮走 1 步;链表头部到链表环入口有a个节点(不计链表环入口节点),链表环有b个节点。(注意a,b都是未知量)
① fast 指针走过链表末端,说明链表无环。若有环,两指针一定会相遇。因为每走 1 轮,fast 与 slow 的间距 +1。
② 两指针在环中第一次相遇,设此时两指针分别走了f,s步
fast走的步数是slow步数的 2 倍:f = 2sfast比slow多走了n个环的长度:f = s + nb(双指针都走过a步,然后在环内绕圈直到重合,重合时fast比slow多走了环的长度整数倍)- 两式相减,得到
s = nb,f = 2nb。即fast和slow指针分别走了2n,n个环的周长(n是未知数)
一个重要结论:任何一个指针从链表头部开始向前走,当它每次走到链表入口节点时,它所走过的步数
k = a + nb(先走a步到入口节点,之后每绕 1 圈环(b步)都会再次到入口节点)。
③ 两指针第一次相遇时,slow指针已经走过了nb步,所以我们只要让 slow 再走 a 步停下来,就可以到环的入口。但是问题是a是未知数,需要找到一个条件来证明snow刚好走过了a步,发现从链表头部开始走到链表环的入口刚好是a步。
slow指针位置不变 ,将fast指针重新指向链表头部节点 ;slow和fast同时每轮向前走 1 步。- 当
fast指针走到f = a步时,slow指针走到步s = a+nb,此时两指针重合,并同时指向链表环入口 。
④ 返回slow指针指向的节点
- 时间复杂度:
- 空间复杂度:
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
while (true) {
if (fast == null || fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
if (fast == slow) break;
}
fast = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
来源:CSDN
作者:magic_jiayu
链接:https://blog.csdn.net/magic_jiayu/article/details/104318354