1. 本题知识点
链表
2. 题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出 null。
3. 解题思路
- 遍历单链表的每个结点
- 如果当前结点地址没有出现在 Set 中,则存入 Set 中
- 如果出现在 Set 中,则当前结点就是环的入口结点
- 整个单链表遍历完,若没出现在 Set 中,则不存在环
4. 代码
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
HashSet<ListNode> set = new HashSet<>();
// 遍历单链表的每个结点
while (pHead != null) {
if (set.contains(pHead)) {
// 出现在 Set 中,则当前结点就是环的入口结点
return pHead;
} else {
// 如果当前结点地址没有出现在 Set 中,则存入 Set 中
set.add(pHead);
pHead = pHead.next;
}
}
// 整个单链表遍历完,若没出现在 Set 中,则不存在环
return null;
}
}