day14 leetcode-hot100-26(链表5)
142. 环形链表 II - 力扣(LeetCode)
1.哈希表
思路
与上一个一模一样,基本上没有区别,就是寻找是否存储过该节点。具体思路如下
day14 leetcode-hot100-25(链表4)-CSDN博客
具体代码
/*** 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) {HashMap<ListNode,Integer> map = new HashMap<>();ListNode p = head;int count = 0;while(p!=null){if(map.containsKey(p)){return p;}map.put(p,count);p=p.next;count++;}return null;}
}