<p>我不完全理解leetcode上<a href="https://leetcode.com/problems/middle-of-the-linked-list/" rel="nofollow noreferrer">"find the middle of linked list"</a>问题的<code>while</code>循环条件:</p>
<blockquote>
<p>Given a non-empty, singly linked list with head node head, return a middle node of linked list.</p>
<p>If there are two middle nodes, return the second middle node.</p>
</blockquote>
<p>对于<code>while</code>循环,我认为条件是</p>
<pre><code>while first and last.next:
</code></pre>
<p>但是当我这么做的时候,我收到一个错误</p>
<pre><code>AttributeError: 'NoneType' object has no attribute 'next'
</code></pre>
<p>条件语句应该是</p>
<pre><code>while last and last.next:
</code></pre>
<p>我不明白为什么。以下是正确while循环的完整代码:</p>
<pre><code># 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
</code></pre>
<p>只要把它画出来就很明显了。考虑两种版本:</p>
<p>A-B-C</p>
<pre><code>first / last / last.next
A B C
B None
</code></pre>
<p>A-B-C-D</p>
<pre><code>first / last / last.next
A B C
B D None
</code></pre>