我不完全理解力扣中的“链表的中间结点”问题中 while
循环的条件:
给定一个带有头结点
head
的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
对于 while
循环,我认为条件应该是
while first and last.next:
但是当我这样做时,我会收到一个错误提示信息,该信息如下:
AttributeError: 'NoneType' object has no attribute 'next'
条件语句应该是
while last and last.next:
我不明白原因。这是完整的代码,包括正确的while循环:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
first = last = head
while last and last.next:
first = first.next
last = last.next.next
return first
last
是None
(即你已经到达链表的末尾),那么你应该结束循环。这就是为什么在last
之前,first
永远不可能等于None
。 - Selcuk