Open rocksc30 opened 1 year ago
Java 哈希表解决方案:
/** * 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) { Set<ListNode> seen = new HashSet<>(); if(head == null || head.next == null){ return null; } ListNode p = head; while(p != null){ if(!seen.add(p)){ return p; } p = p.next; } return null; } }
Java 哈希表解决方案: