【发布时间】:2019-04-16 04:15:35
【问题描述】:
在检查链表的中间节点时,我对 while 循环条件在链表中的工作方式感到困惑
这是我找到链表中间节点的正确代码
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class linkedList(object):
def __init__(self):
self.head = None
def append(self, data):
node = Node(data)
if self.head == None:
self.head = node
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
def middle(self):
first = self.head
second = self.head
while second and second.next:
second = second.next.next
first = first.next
print(first.data)
如果我将 while 循环更改为
while second:
或
while second.next:
我收到一条错误提示
AttributeError: 'NoneType' object has no attribute 'next' on line 24
我只是想知道为什么同时拥有second 和second.next 很重要
【问题讨论】:
-
因为只有当
second有一个有效值时,你才能调用second.next,同样,只有当你有一个有效的second.next时,你才能调用second.next.next -
在下面查看我的答案!
标签: python python-3.x linked-list