Lc142 环形链表Ⅱ

Lc 环形链表Ⅱ

思路:

1.判断链表是否成环-- 定义快慢指针,一个每次走两步,一个每次走一步,相对就是多走一步,所以一定会相遇。若fast != null && fast.next != null 时对两指针进行移动,若一直到slow与fast相遇(此时一定在环中)从而证明有环,如果 fast == null || fast.next == null 直接跳出循环,则没环。

2.判断出有环之后

此时fast == slow 在A点相遇,根据fast速度为slow两倍,即路程也为两倍,则有

//(x + y) * 2 == x + n * (y + z) + y
//x == n * (y + z) + y == (n - 1) * (y + z) + z

也就是说走了x和走了(n - 1)圈+z的路程是一样的,即 从head出发走x与从break的相遇点A出发绕圈再次相遇时刚好相遇到环的起点B

代码:

/**
 * 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) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;

            //快慢指针相遇(一定是从环里相遇,从而证明链表有环)
            if (fast == slow){
                ListNode index1 = head;
                ListNode index2 = fast;
                while (index1 != index2){
                    index1 = index1.next;
                    index2 = index2.next;
                }

                return index1;
            }
        }

        return null;
    }
}

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值