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 是 针对奇数个的时候

posted @ 2019-01-25 22:57  dgi  阅读(143)  评论(0编辑  收藏  举报