python实现找到链表中环的入口结点

题目来自LeetCode 142. Linked List Cycle II 也是典型的面试用的编程题.
牛客网也有相应的题目,但是我摸索不出判题的标准,似乎是对于python的null和None的定义有些偏颇,有在牛客上通过的python solution麻烦分享,谢谢.

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        try:
            slow = head.next
            fast = head.next.next
            while fast != slow:
                slow = slow.next
                fast = fast.next.next
            h = head
            while h != fast:
                h = h.next
                fast = fast.next
            return  h
        except:
            return None

题目要点:
1. 首先是看了LeetCode大神StefanPochmann 的discussion,他对于python的理解确实很变态,几乎达到了代码美观和算法高效的平衡.每次答题区有他的答案总能醍醐灌顶.使用try…except来做链表题目是再适合不过. 源自document中的思想Easier to ask for forgiveness than permission. 请求原谅总比请求允许要简单得多,似乎已经可以上升到人生格言的水平(先行动了再说).

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false.

  1. 题目的代码实现并不难,只是原理比较难理解.问题分为两个部分解析:
    1) 判断链表存在回环
    2) 找到回环的入口

猜你喜欢

转载自blog.csdn.net/m0_37422289/article/details/79944068