給一個鏈表,若其中包含環,請找出該鏈表的環的入口結點,不然,輸出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