双指针检测数组、链表、图中的环

双指针检测数组、链表、图中的环

问题
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;
  1. 我们已经得到了结论a=c,那么让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。
  2. 在上一个问题的最后,将c段中Y点之前的那个节点与Y的链接切断即可。
  3. 如何判断两个单链表是否有交点?一个链表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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值