题目描述:
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路1:
自然而然想到使用容器(列表、堆栈、数组等)保存链表节点,在保存进入容器之前判断容器内是否已经存在,如果存在则直接返回该节点,该节点就是环的入口节点
class ListNode:
def __init__(self, x):
self.val = x
self.next= None
def EntryNodeOfLoopByCollections(pHead):
if pHead == None:
return None
cur = pHead
stack = []
while cur:
if cur not in stack:
stack.append(cur)
cur = cur.next
else:
return cur
return None
测试:
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
f = ListNode(6)
g = ListNode(7)
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
f.next = c
loopNode = EntryNode