Linked List Cycle II

Description:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

问题描述:

给定一条链表,判断是否有环,函数返回环开始的第一个结点(也就是环的入口处)

解法一:

思路:

这个问题算是之前判断链表是否有环问题的一个拓展。解决这个问题的思路分为两步,第一步是个追击问题(找到快慢指针第一次相遇的地方),第二步是个相遇问题(找到链表环的入口处)。
现在需要设定三个指针,一个快(fast)指针,一个慢(slow)指针,一个start指针。设环形链表的长度为r。
追击问题: 快指针走2k步时,慢指针走了k步,由于2k-k= nr,那么当k = r时,快慢指针第一次相遇。假设次数慢指针距离环的入口处为m , start指针距离环的入口处为s .
相遇问题:慢指针一次走一步,start指针也是一次走一步,由于s + m = nr , 所以两个指针一定会在环的入口处相遇。否则链表无环。

Code:

/**
 * 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 || head.next == null)
            return null;

        ListNode fast = head , slow = head , start = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                while(slow != start){
                    slow = slow.next;
                    start = start.next;
                }
                return start;
            }
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值