leetcode -- 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         if(head == null){
 6             return null;
 7         }
 8         
 9         ListNode fast = head, slow = head;
10         while(fast.next != null && fast.next.next != null){
11             fast = fast.next.next;
12             slow = slow.next;
13             if(fast == slow){
14                 break;
15             }
16         }
17         
18         if(fast.next == null || fast.next.next == null){
19             return null;
20         }
21         
22         fast = head;
23         while(fast != slow){
24             fast = fast.next;
25             slow = slow.next;
26         }
27         
28         return slow;
29     }
30     
31 }

 

posted @ 2013-11-15 16:12  feiling  阅读(212)  评论(0编辑  收藏  举报