链表环中的入口节点python
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路:既然是存在环,我们去循环遍历的时候,肯定能够再次读取到入口节点,我们根据这一点来写
代码如下:
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here a=[] while pHead: if pHead not in a: a.append(pHead) else: return pHead pHead=pHead.next