劍指向Offer-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

思路

該鏈表的環的入口結點,即尾節點指向頭節點的鏈表入口

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        # write code here
        my_list = []
        p = pHead
        while p:
            if p not in my_list:
                my_list.append(p) 
            else:
                return p 
            p = p.next # 遍歷鏈表,將結果存入列表
        else:
            return None
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章