Leetcode 142: Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public int val;
 5  *     public ListNode next;
 6  *     public ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode DetectCycle(ListNode head) {
14         if (head == null) return null;
15         
16         ListNode fast = head, slow = head, entry = head;
17         
18         while (fast.next != null && fast.next.next != null)
19         {
20             fast = fast.next.next;
21             slow = slow.next;
22             
23             // found a cycle
24             if (slow == fast)
25             {
26                 while (slow != entry)
27                 {
28                     slow = slow.next;
29                     entry = entry.next;
30                 }
31                 
32                 return entry;
33             }
34         }
35         
36         return null;
37     }
38 }

 

posted @ 2017-11-23 02:00  逸朵  阅读(110)  评论(0编辑  收藏  举报