[英]How to return the middle node of a linked list
在检查链表的中间节点时,我对链接列表中的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
很重要
该解决方案使用两个指针。 第一个一步采取一步,一次采用第二步。 但是,在采取两个步骤时,需要验证两件事:
如果你跳过一个检查,它将进入循环但在边界条件下它找不到下一个。 为了说明:如果有4个节点并且你只在第3个节点检查second.next
你将有second.next
作为有效,你将进入while
循环但在你内部直接访问second.next.next
F,S | 1 - > 2 - > 3 - > 4 - >无
对于初学者来说,你的append方法不起作用,并且陷入无限循环中,因为在添加第一个元素时你不会退出追加。 正确的版本是
def append(self, data):
node = Node(data)
if self.head == None:
self.head = node
return
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
至于你的另一个问题,我们想找到偶数和奇数列表的循环中间, second
second.next
覆盖奇数列表的情况, second
覆盖偶数列表的情况,因为第二个指针将指向null ,或者它本身就是null,如果你只使用其中一个,你将得到你描述的错误,因此你需要在while循环中同时具备这两个条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.