https://leetcode.com/problems/linked-list-cycle/
该题两种解法,第一种采用hashMap(其实这里用HashSet就行了),存储当前节点,遍历一次找到是否存在当前节点在表中,存在马上返回true,都不存在,则返回false。
public boolean hasCycle(ListNode head) {
// 将链表中的元素一个个读取到hashmap中,判断是否存在
Map<ListNode, Integer> map = new HashMap<>();
ListNode curr = head;
while(curr != null) {
if (map.containsKey(curr)) return true;
map.put(curr, curr.val);
curr = curr.next;
}
return false;