Leetcode 142. 环形链表 II

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

说明:不允许修改给定的链表。

进阶:
你是否可以不用额外空间解决此题?

 
思路:用HashMap遍历一遍链表,碰到未hash过的节点值就将他扔进hash里面
如果已经hash过了就证明这个点就是环的第一个节点
 
 1 ListNode detectCycle(ListNode head) {
 2         HashMap <ListNode,Integer> map=new HashMap<>();
 3         if(head==null||head.next==null)
 4             return null;
 5         
 6         while(head==null)
 7         {
 8             if(map.containsKey(head)==false)
 9             {
10                 map.put(head, 1);
11                 head=head.next;
12                 continue;
13             }
14             return head;
15         }
16         
17         return null;
18     }
View Code
原文地址:https://www.cnblogs.com/tijie/p/9943493.html