Python 从链接列表中删除节点不起作用
我下面删除链接列表中节点的代码无效,因为它删除了我要删除的索引的错误索引Python 从链接列表中删除节点不起作用,python,linked-list,Python,Linked List,我下面删除链接列表中节点的代码无效,因为它删除了我要删除的索引的错误索引 class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None self.tail=None def Addnode(self,data):
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
def Addnode(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
if self.tail!=None:
self.tail.next=new_node
self.tail=new_node
def removenode(self,index):
new_n=self.head
count=0
while count!=index:
new_n=new_n.next
count+=1
new_n.next=new_n.next.next
def Printlist(self):
node=self.head
while node!=None:
print(node.data)
node=node.next
List=LinkedList()
List.Addnode(1)
List.Addnode(2)
List.Addnode(3)
List.Addnode(4)
List.removenode(1)
List.Printlist()
所以这应该删除索引1处的节点,即2,但是它会删除3,并打印1,2,4,甚至不是5?我很困惑为什么会发生这种情况?您的删除功能做得太过分了。让我们浏览一下,删除第一个节点(如代码中所示)
new\n
现在指向头部节点。这是我们想要的,所以它是正确的
count=0
将计数初始化为零。这也是正确的,因为当前节点是节点零
while count!=index:
new_n=new_n.next
count+=1
这就是我们得到意外行为的地方。在第一次迭代中(因为0!=1),我们进入循环。现在new\n
指向列表中的第二个元素(索引1),count
为1
现在我们再次尝试循环条件count
现在等于index
,因此我们打破了循环
当前的new\n
现在指向列表中的第二个元素(索引1),因此new\n.next=new\n.next.next
将下一个元素更改为其当前下一个元素之后的元素。这是从链表中删除一个元素的方法,但是我们只删除了一个元素(我们遍历链表太远了)。要解决此问题,请尝试以下代码:
def removenode(self,index):
# catch the edge condition where we're removing the first node
if index==0
self.head = self.head.next
else
new_n=self.head
count=1
while count!=index:
new_n=new_n.next
count+=1
new_n.next=new_n.next.next
免责声明:我在这台计算机上没有Python,所以我无法测试代码,但希望通过这种方式分解代码会有所帮助 您的删除功能做得太过分了。让我们浏览一下,删除第一个节点(如代码中所示)
new\n
现在指向头部节点。这是我们想要的,所以它是正确的
count=0
将计数初始化为零。这也是正确的,因为当前节点是节点零
while count!=index:
new_n=new_n.next
count+=1
这就是我们得到意外行为的地方。在第一次迭代中(因为0!=1),我们进入循环。现在new\n
指向列表中的第二个元素(索引1),count
为1
现在我们再次尝试循环条件count
现在等于index
,因此我们打破了循环
当前的new\n
现在指向列表中的第二个元素(索引1),因此new\n.next=new\n.next.next
将下一个元素更改为其当前下一个元素之后的元素。这是从链表中删除一个元素的方法,但是我们只删除了一个元素(我们遍历链表太远了)。要解决此问题,请尝试以下代码:
def removenode(self,index):
# catch the edge condition where we're removing the first node
if index==0
self.head = self.head.next
else
new_n=self.head
count=1
while count!=index:
new_n=new_n.next
count+=1
new_n.next=new_n.next.next
免责声明:我在这台计算机上没有Python,所以我无法测试代码,但希望通过这种方式分解代码会有所帮助 也许添加编程语言标记会有帮助,这在Python中是吗?是的,很抱歉,也许添加编程语言标记会有帮助,这在Python中是吗?是的,很抱歉。哇,非常感谢您的详细解释!它很管用,谢谢!哇,非常感谢你的详细解释!它很管用,谢谢!