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?


判断一个链表中是否有环存在,并且输出环的起始点。我们用快慢指针fast,slow来判断是否有环存在,如果它们可以相遇就说明有环存在,如果不能相遇说明没有环存在。它们相遇之后,图中的meet点是它们的相遇点,假设join为环的起始点,我们假设head到join的距离为a, join到meet的距离为b(逆时针),meet到join的距离为c(逆时针)。如果它们相遇,那么fast走过的路程是slow走过的两倍,所以a + b + c + b = 2 ( a + b),即a = c。有了这个关系我们只需要用两个指针一个从相遇点出发,另一个从头结点出发,它们相遇的点就是环的起始点。代码如下:
/**
 * 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;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast) 
                break;
        }
        if(fast != slow) return null;
        fast = head;
        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276311
今日推荐