leecode142

给定链表,返回循环开始的节点。如果没有循环,则返回null

唯一的问题就是判断是否已经出现过了

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> values = new HashSet<ListNode>();
while(head!=null){
if (values.contains(head)){
return head;
}
values.add(head);
head = head.next;
}
return null;
}
}