lintcode链表的中点

第一次写的,如果fast.next是none,那么fast.next.next会报错

    def middleNode(self, head):
        # write your code here
        i = 0
        if head.val != None:
            slow = head
            fast = head
            while fast.next.val != None:
                slow = slow.next
                fast = fast.next
                while fast.next.val != None:
                    fast = fast.next
            return slow.val
        else:
            return None

第二次写的。需要先判断fast.next.next不为None,再给slow往下走一步。判断链表为空,应该判断head是否为none ,不应该判断head.next。

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: the head of linked list.
    @return: a middle node of the linked list
    """
    def middleNode(self, head):
        # write your code here
        if not head.next:
            return None
        else:
            slow = head
            fast = head
            while  fast.next:
                slow = slow.next
                fast = fast.next
                while fast.next:
                    fast = fast.next
                    break
            return(slow)

第三次

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: the head of linked list.
    @return: a middle node of the linked list
    """
    def middleNode(self, head):
        # write your code here
        if not head:
            return None
        else:
            slow = head
            fast = head
            while  fast.next:
                fast = fast.next
                if fast.next:
                    slow = slow.next
                    fast = fast.next
            return(slow)

通过
查看别人的写法,先判断fast.next,用and连接判断fast.next.next。一条就搞定。

class Solution:
    """
    @param head: the head of linked list.
    @return: a middle node of the linked list
    """
    def middleNode(self, head):
        # write your code here
        if not head:
            return None
        else:
            slow,fast = head,head
            while fast.next and fast.next.next:
                slow = slow.next
                fast= fast.next.next
            return slow
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值