繁体   English   中英

从链接列表中删除节点不起作用

[英]Deleting a Node from a Linked List is not working

我下面用于删除链表中节点的代码无法正常工作,因为它正在删除我要删除的索引的错误索引。

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的Node(即2),但是却删除了3,并打印1,2,4,甚至不打印5? 我很困惑为什么会这样?

您的删除功能实在太过分了。 让我们遍历它,删除第一个节点(如代码中所示)。

new_n=self.head

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,因此我无法测试代码,但希望以这种方式将其分解会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM