第一次写的,如果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