JZ23 链表中环的入口结点

JZ23 链表中环的入口结点
JZ23 链表中环的入口结点_第1张图片
JZ23 链表中环的入口结点_第2张图片

class Solution:
    def EntryNodeOfLoop(self, pHead):
        p1 = p2 = pHead # p2快指针  p1慢指针
        while p2:
            p1,p2 = p1.next,p2.next
            if not p2: # 要是无环 一定快指针先到None
                return None
            p2 = p2.next
            if p1 == p2: # 相遇必然有环 (直接开始找环)
                p1 = pHead  # p1回到起点  p2留在相遇点
                while p1 != p2:  # 同步后移 必然相遇于环起点
                    p1,p2 = p1.next,p2.next
                return p1  # 环入口

完整代码:

from myutils.MyList import *
class Solution:
    def EntryNodeOfLoop(self, pHead):
        p1 = p2 = pHead # p2快指针  p1慢指针
        while p2:
            p1,p2 = p1.next,p2.next
            if not p2: # 要是无环 一定快指针先到None
                return None
            p2 = p2.next
            if p1 == p2: # 相遇必然有环 (直接开始找环)
                p1 = pHead  # p1回到起点  p2留在相遇点
                while p1 != p2:  # 同步后移 必然相遇于环起点
                    p1,p2 = p1.next,p2.next
                return p1  # 环入口





ph1,t1 = Create2([])
ph2,t2 = Create2([2])

if ph2:
    if t1:
        t1.next = ph2
    t2.next = ph2

# pt = ph1
# for i in range(10):
#     print(pt.val,end=' ')
#     pt = pt.next

pHead = None
if ph1:
    pHead = ph1
else:
    pHead = ph2

ans = Solution().EntryNodeOfLoop(pHead)
if ans:
    print(ans.val)
else:
    print("null")

# a = b = c =  3
# print('\n',a,b) # 3,3  确实可以直接这么赋值

MyList.py

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def show(self):
        p = self
        while p is not None:
            print(p.val, end=' ')
            p = p.next
        print()


# 只返回头节点
def Create(data):
    # print('data',data)
    if len(data) < 1:
        return None

    head = ListNode(data[0])
    tail = head
    for i in range(1, len(data)):
        tail.next = ListNode(data[i])
        tail = tail.next
    return head


# 返回头节点和尾节点
def Create2(data):
    # print('data',data)
    if len(data) < 1:
        return None, None

    head = ListNode(data[0])
    tail = head
    for i in range(1, len(data)):
        tail.next = ListNode(data[i])
        tail = tail.next
    return head, tail

# list1 = Create([1, 2, 3])
# list1.show()



你可能感兴趣的:(#,算法,剑指,python,算法)