42. Linked List Cycle II - Jake blog - Java coding practice log (2017)" /> 42. Linked List Cycle II - Jake blog - Java coding practice log (2017)" />

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?

Approach:

The difficulty of this problem lies in returning to the cycle begins. We previously used fast and slow pointers to determine if a cycle had occurred, but how do we return to the initial point? I found a relatively easy-to-understand explanation online:

When fast and slow meet at point p, the length they have run are ‘a+2b+c’ and ‘a+b’.
Since the fast is 2 times faster than the slow. So a+2b+c == 2(a+b), then we get ‘a==c’.

142. Linked List Cycle II

/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; fast = fast.next.next; if(slow == fast){ ListNode real = head; while(real != slow){ real =real.next; slow = slow.next; } return real; } } return null; } }

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:「142. Linked List Cycle II」

200
0 1 200

Further Reading

Post a reply

Log inYou can only comment after that.

Comment list (1 item)

Share this page
Back to top