Linked List Cycle II

public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. if there is no cycle, return null
     */
		public ListNode detectCycle(ListNode head) {
			if (head == null) {
				return null;
			}
			ListNode slow = head, fast = head;
			while (fast != null && fast.next != null) { //corner case → .next 出现都要判断
				slow = slow.next;
				fast = fast.next.next;
				if (slow == fast) {
					break;
				}
			}
			if (fast == null || fast.next == null) {
				//no cycle 
		return null;	
			}
			
			//pointers in same speed 
			ListNode a = head, b = slow;
			while (a != b) {
				a = a.next;
				b = b.next;
			}
			return a;
		}
}

最后更新于

这有帮助吗?