[英]Can't remove first node in linked list
I'm trying to make a linked list class in python (pointless I know, but it's a learning exercise), and the method I have written to remove a node doesn't work if I try to remove the first element of the linked list. 我正在尝试在python中创建一个链表类(我知道毫无意义,但这是一个学习练习),如果尝试删除链表的第一个元素,我编写的删除节点的方法将不起作用。 If the node to be removed is anywhere else in the linked list the method works fine. 如果要删除的节点在链表中的其他位置,则该方法可以正常工作。 Can someone give me some insight as to where I've gone wrong? 有人可以给我一些有关我哪里出问题的见解吗?
Here's my code thus far: 到目前为止,这是我的代码:
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __repr__(self):
return repr(self.data)
def printNodes(self):
while self:
print self.data
self = self.next
def removeNode(self, datum):
"""removes node from linked list"""
if self.data == datum:
return self.next
while self.next:
if self.next.data == datum:
self.next = self.next.next
return self
self = self.next
Modify removeNode
so that it always returns the head of the linked list and then assign the result back to your head node. 修改removeNode
,使其始终返回链接列表的头部,然后将结果分配回您的头部节点。 Like so: 像这样:
def removeNode(self, datum):
"""removes node from linked list and returns head node"""
head = self
curr_node = self
if curr_node.data == datum:
head = curr_node.next
else:
while curr_node.next:
if curr_node.next.data == datum:
curr_node.next = self.next.next
break
curr_node = curr_node.next
return head
Or, if you want to avoid having to assign the result of removeNode
back to head: 或者,如果您希望避免必须将removeNode
的结果分配回头:
def removeNode(self, datum):
"""removes node from linked list"""
curr_node = self
if curr_node.data == datum:
# steals the the data from the second node
curr_node.data = curr_node.next.data
curr_node.next = curr_node.next.next
else:
while curr_node.next:
if curr_node.next.data == datum:
curr_node.next = curr_node.next.next
break
curr_node = curr_node.next
Note: I assigned self
to curr_node
because it felt wrong to modify self
. 注意:我将self
分配给curr_node
因为修改self
感觉不对。
As shown in your code, removeNode
method returns the new first node of the link list. 如您的代码所示, removeNode
方法返回链接列表的新第一个节点。 You should use head = head.removeNode(1)
rather than just call the method. 您应该使用head = head.removeNode(1)
而不是仅调用方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.