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.

代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode detectCycle(ListNode head) {
14         
15         Map<ListNode,ListNode> map=new HashMap<>();
16         while(head!=null)
17         {
18             if(map.get(head)!=head)
19             map.put(head,head);
20             else
21             return head;
22             head=head.next;
23         }
24         return null;
25     }
26 }