rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

142. 环形链表 II #13

Open rocksc30 opened 1 year ago

rocksc30 commented 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;
    }
}