给一个链表,若其中包含环,请找出该链表的环的入口结点,不然,输出null。python
时间限制:1秒;空间限制:32768K;本题知识点:链表app
用一个list记录链表结点,空间复杂度大。oop
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here l = [] #记录节点 if pHead == None: return None while pHead.next != None: for i in range(len(l)): if pHead==l[i]: return pHead l.append(pHead) pHead = pHead.next return None
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here if pHead == None: return "null" # 找环中相汇点 if pHead.next!=None and pHead.next.next!=None: #先跑一次以知足循环条件 fast = pHead.next.next slow = pHead.next else: return None while fast != slow: if fast.next!=None or fast.next.next!=None: fast = fast.next.next slow = slow.next else: return None # 找环的入口 fast = pHead while fast != slow: fast = fast.next slow = slow.next return slow