876. Middle of the Linked List

Posted captain-dl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 是 针对奇数个的时候

以上是关于876. Middle of the Linked List的主要内容,如果未能解决你的问题,请参考以下文章

876. Middle of the Linked List

876. Middle of the Linked List

[LeetCode] 876. Middle of the Linked List

leetcode-876 Middle of the Linked List

[LeetCode] 876. Middle of the Linked List

876. Middle of the Linked List - LeetCode