*Linked List Cycle II - Leetcode

/**
 * 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 faster = new ListNode(-1);
        ListNode slower = new ListNode(-1);
        faster = head;
        if(faster == null)
           return head;
           
        slower = faster;
        boolean isCycle = false;
        while(faster != null && faster.next != null){
            faster = faster.next.next;
            slower = slower.next;
            if(faster == slower){
                isCycle = true;
                break;
            }
        }
        
        <span style="background-color: rgb(255, 255, 51);">while(isCycle){
            if(slower == head)
                return head;
            head = head.next;
            slower = slower.next;
        }</span>
        return null;
    }
}


分析:不适用额外的空间,找圈的起点。圈的起点有什么特征呢?

一般节点都是只有一个指针(上一个节点的)指向它,圈的开头,除了上一个节点,还有一个尾巴节点指向它。这样圈的开头是唯一一个有两个指针指向它的节点。。。。。???这个解法待续~

剩下一个数学解法。快的走的路程始终是慢的2倍。当快的走了x+a+r时候,慢的走了x+a. 这里r=x+a;(x是list起点到圈起点的距离;a是圈起点到相遇点的距离;r是圈的周长)。解法就是找到相遇点之后,从相遇点同步同速度向前走,下一个碰头的地方就是圈起点。

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?


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值