Linked List Cycle II
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?
思想: 从开头到交点的距离是交点到返回来交点的距离的n倍,则从开头出发和头交点出发,则一定会在分叉口碰撞;先找到相交点
- public ListNode detectCycle(ListNode head) {
- if(head==null || head.next==null) return null;
- ListNode slow=head;
- ListNode fast=head;
- while(fast!=null && fast.next!=null) {
- fast=fast.next.next;
- slow=slow.next;
- if(fast==slow) break;
- }
- if(fast==null || fast.next==null) return null;
- ListNode p=head;
- while(p!=fast) {
- p=p.next;
- fast=fast.next;
- }
- return p;
- }