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?

 

 1 public class Solution {
 2     public ListNode detectCycle(ListNode head) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         ListNode fast = head, slow = head;
 6         while(fast != null && fast.next != null){
 7             fast = fast.next.next;
 8             slow = slow.next;
 9             if(fast == slow){
10                 slow = head;
11                 while(fast != slow){
12                     fast = fast.next;
13                     slow = slow.next;
14                 }
15                 return slow;
16             }
17         }
18         return null;
19     }
20 }

 

posted on 2013-11-26 09:33  Step-BY-Step  阅读(135)  评论(0编辑  收藏  举报

导航