双指针检测数组、链表、图中的环
双指针检测数组、链表、图中的环
问题
Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
如何判断一个单链表中有环?
Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?
如何找到环的第一个节点?
分析
假设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
1.因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
我们发现L=b+c=a+b,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。
代码:
public static ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (true) {
if (fast == null || fast.next == null) {
return null; //遇到null了,说明不存在环
}
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
break; //第一次相遇在Z点
}
}
//slow从头开始走,再次相遇位置即为环起点
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
循环部分也可以这么写:
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) break;
}
//交点位置为null或者最后一个节点表示无环
if (fast == null || fast.next == null) return null;
- 我们已经得到了结论a=c,那么让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。
- 在上一个问题的最后,将c段中Y点之前的那个节点与Y的链接切断即可。
- 如何判断两个单链表是否有交点?一个链表a->b->c->b,另一个链表c->b->a->b, 如果相遇在null前则返回节点。
//Leetcode 160
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA, b = headB;
if(headA == null || headB == null) return null;
while(a != b){
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
这么写也可以
ListNode a = headA, b = headB;
while(a != b ){
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
if(a == null || b == null) return null;
return a;