力扣:142. 环形链表 II

This commit is contained in:
huangge1199 2021-02-10 08:46:56 +08:00
parent d901a58b1e
commit a2a56d89c7

View File

@ -0,0 +1,38 @@
package com.code.leet.study.t20210209;
import com.code.leet.entiy.ListNode;
import java.util.HashSet;
import java.util.Set;
/**
* 给定一个链表返回链表开始入环的第一个节点 如果链表无环则返回 null
* <p>
* 为了表示给定链表中的环我们使用整数 pos 来表示链表尾连接到链表中的位置索引从 0 开始 如果 pos -1则在该链表中没有环注意pos 仅仅是用于标识环的情况并不会作为参数传递到函数中
* <p>
* 说明不允许修改给定的链表
* <p>
* 进阶
* <p>
* 你是否可以使用 O(1) 空间解决此题
* <p>
* 来源力扣LeetCode
* 链接https://leetcode-cn.com/problems/linked-list-cycle-ii
* 著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
*/
public class DetectCycle {
/**
* 142. 环形链表 II
*/
public ListNode detectCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (!set.add(head)) {
return head;
} else {
head = head.next;
}
}
return null;
}
}