1.题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
2.算法描述
灵活用集合
1.
初
始
化
一
个
结
点
集
合
容
器
,
用
来
装
结
点
。
\red{1.初始化一个结点集合容器,用来装结点。}
1.初始化一个结点集合容器,用来装结点。
2.
遍
历
链
表
中
的
结
点
,
并
将
结
点
装
入
集
合
,
当
装
入
某
个
结
点
时
,
\red{2.遍历链表中的结点,并将结点装入集合,当装入某个结点时,}
2.遍历链表中的结点,并将结点装入集合,当装入某个结点时,
集
合
中
已
经
有
该
结
点
,
则
该
结
点
是
链
表
环
的
入
口
;
否
则
返
回
n
u
l
l
\red{集合中已经有该结点,则该结点是链表环的入口;否则返回null}
集合中已经有该结点,则该结点是链表环的入口;否则返回null
3.代码描述
3.1.Java代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead){
Set<ListNode> set = new HashSet<>();
while(pHead != null){
if(set.contains(pHead))
return pHead;
set.add(pHead);
pHead = pHead.next;
}
return null;
}
}
3.2.Python代码
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
s = set()
while pHead:
if pHead in s:
return pHead
s.add(pHead)
pHead = pHead.next
return None