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倍,则从开头出发和头交点出发,则一定会在分叉口碰撞;先找到相交点

  1. public ListNode detectCycle(ListNode head) {
  2. if(head==null || head.next==null) return null;
  3. ListNode slow=head;
  4. ListNode fast=head;
  5. while(fast!=null && fast.next!=null) {
  6. fast=fast.next.next;
  7. slow=slow.next;
  8. if(fast==slow) break;
  9. }
  10. if(fast==null || fast.next==null) return null;
  11. ListNode p=head;
  12. while(p!=fast) {
  13. p=p.next;
  14. fast=fast.next;
  15. }
  16. return p;
  17. }
posted @ 2014-07-28 20:58  purejade  阅读(64)  评论(0编辑  收藏  举报