美文网首页
2019-05-18LeetCode141. 环形链表

2019-05-18LeetCode141. 环形链表

作者: mztkenan | 来源:发表于2019-05-18 20:29 被阅读0次

    25min,双指针,对链表的处理,关键点在于a.next 的时候 a 不能是None,特殊情况head 为空

    class Solution(object):
        def hasCycle(self, head):
            """
            :type head: ListNode
            :rtype: bool
            """
            if(head!=None):pos=head.next
            else:return False  # head=None
            while(pos!=head):
                if(head!=None):
                    head=head.next
                else:return False
                if(pos!=None and pos.next!=None):
                    pos=pos.next.next
                else:return False
            return True
    

    使用try catch简直优雅,因为所有的异常情况都表示无环!excellent!
    Easier to ask for forgiveness than permission."

    class Solution(object):
        def hasCycle(self, head):
            """
            :type head: ListNode
            :rtype: bool
            """
            try:
                fast=head.next
                while(fast!=head):
                    fast=fast.next.next
                    head=head.next
                return True
            except:
                return False
    

    相关文章

      网友评论

          本文标题:2019-05-18LeetCode141. 环形链表

          本文链接:https://www.haomeiwen.com/subject/cgcxzqtx.html