Linked List Cycle II

Linked List Cycle II

  Total Accepted: 17710  Total Submissions: 57697 My Submissions

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?

Have you been asked this question in an interview? 

Discuss

一开始看错了,以为是只要求是否有环路。还是相对比较简单的题目,首先使用快慢指针,一个走两步,一个走一步。如果没环路,快指针会先到。如果有环,两个指针总会相遇。在找到环之后,这两个相遇的指针肯定在环路当中,于是可以在用第三个指针,先走一圈,如何走一圈,很简单。然后再开第四个指针,第三个指针总比第四个指针快一圈,于是同时走,会在环路产生的地方相遇。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
 //16:18 -> 16:42 pass
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode n1,n2,n3;
        n1 = n2 = head;
        if(head==null)
        {
            return null;
        }
        while(true)
        {
            n2 = n2.next;
            if(n2!=null)
            {
                n2 = n2.next;
                //whithout this sentence;
                if(n2==null)
                {
                    break;
                }
            }else
            {
                break;
            }
            n1 = n1.next;
            // there is a cycle
            if(n1==n2)
            {
                n3 = head.next;
                n2 = n2.next;
                //n2 move a cycle, and the n3 move a cycle too
                while(n2!=n1)
                {
                    n2 = n2.next;
                    n3 = n3.next;
                }
                //n3 just one cycle faster than n2;
                n2 = head;
                while(n2!=n3)
                {
                    n3 = n3.next;
                    n2 = n2.next;
                }
                return n2;
            }
        }
        return null;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值