leetcode [#142]

目录

题目

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


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/

public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode p = head;
HashSet<ListNode> arr = new HashSet<>();

while(p != null){
if(arr.add(p) == false) {
return p;
}
p = p.next;
}
return null;
}
}

注意事项

  1. 在141题的基础上,这题就很简单了。141题中当arr.add(p)方法返回为false,说明该节点已经被记录过了,说明该节点被指向了2次,而这刚好正是循环的开始,那现在直接返回该节点即可。