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

2024-06-28 20:57:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我下面删除链接列表中节点的代码不起作用,因为它删除了要删除的索引的错误索引

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?我不明白为什么会这样


Tags: selfnonenodenewdata节点defcount
1条回答
网友
1楼 · 发布于 2024-06-28 20:57:48

你的删除功能做得太过分了。让我们浏览一下,删除第一个节点(如代码中所示)

new_n=self.head

new_n 现在指向head节点。这就是我们想要的,所以这是正确的

count=0

将计数初始化为零。这也是正确的,因为当前节点是node zero

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

相关问题 更多 >