leetcode 142. Linked List Cycle II

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

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?



思路基于 141. Linked List Cycle 的快慢指针。定义一个慢指针每次走一步,快指针每次走两步。如果他们能相遇,那必定快指针走过的路径是慢指针的2倍。在定义一个指针从头开始出发,不难计算出,他和慢指针相遇时,就是圈的起始节点。

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null) return null;
        ListNode slow=head,quick=head;
        do{
            slow=slow.next;
            if(quick!=null&&quick.next!=null){
               quick=quick.next.next; 
            }else{
                return null;
            }
        }while(quick!=slow);
        quick=head;
        while(quick!=slow){
            quick=quick.next;
            slow=slow.next;
        }
        return slow;
    }
}

猜你喜欢

转载自blog.csdn.net/yaoct/article/details/80386363