Linked List Cycle II -LeetCode
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?
思路:
跟Linked List Cycle一样,用两个pointer,一快一慢来判断有没有cycle。一旦两个pointer重合,那么这个list肯定有环
在不允许使用extra space的情况下,可以运用一些简单的数学来推测出cycle的起始点。假设这个起始点在离头结点K个节点的位置,而两个节点相遇的点离环的起始节点距离为x。一旦两个pointer重合,那么快的那个pointer已经走过了k+2(n-k)+x, 而慢的那个pointer走过了k+(n-x)的距离。由于两个节点的速度差为2,所以可以推断出x=k.也就是说,当我们找到了两个节点的相遇节点后,把其中一个节点移到头结点,再以相同的速度往前走,第二次相遇的节点就是cycle的起始节点。
/** * 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) return null; ListNode fast=head; ListNode slow=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; } slow=head; while(fast!=slow){ fast=fast.next; slow=slow.next; } return slow; } }