zoukankan      html  css  js  c++  java
  • 876. Middle of the Linked List

    题目来源:
     
    自我感觉难度/真实难度:
     
    题意:
     
    分析:
     
    自己的代码:
    import math
    class Solution:
        def middleNode(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            n=0
            head1=head
            while head1:
                head1=head1.next
                n+=1
            for i in range(math.ceil(n/2)):
                head=head.next
            return head.val
    代码效率/结果:
     
    优秀代码:
    class Solution(object):
        def middleNode(self, head):
            slow = fast = head
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next
            return slow
    代码效率/结果:
     
    自己优化后的代码:
    class Solution:
        def middleNode(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            fast=slow=head
            while fast and fast.next:
                fast=fast.next.next
                slow=slow.next
            return slow
     
    反思改进策略:
    写题时间时长:

    1.取linked list 中间值,用快慢指针

    2.停止的条件是fast.next=none 和fast 一起来判断,因为fast是对偶数个,fast.next 是 针对奇数个的时候

  • 相关阅读:
    病毒
    最短母串
    单词
    Censoring
    玄武密码
    Keywords Search
    聚会
    异象石
    暗的连锁
    pat 1048. Find Coins (25)
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10322248.html
Copyright © 2011-2022 走看看