在Python中从链接列表中删除头节点

时间:2019-08-09 20:17:22

标签: python python-3.x

我一直在研究Python中的链表。我能够创建节点,链接节点并添加新节点,但是我确实停留在删除节点上,特别是当节点中存在的元素与标头(列表中的第一个节点)匹配的情况下(根指针为指向它。

我写了一个条件来检查输入元素是否与标头节点中的元素匹配,如果找到了,我将根指针更改为下一个节点指针,但仍然无法删除该节点。

以下是我创建的删除节点的功能:

import copy
class Node:
      def __init__(self,data=None):
        self.data=data
        self.pointer=None

class Llist:
      def __init__(self):
        self.rootpointer=None

      def addlist(self,newdata):
        self.newdata=newdata
        node4=Node(newdata)
        node4.pointer=self.rootpointer
        self.rootpointer=node4

      def Dispaylist(self):
        self.cpyrootpointer=copy.deepcopy(self.rootpointer)
        while self.cpyrootpointer is not None :
          print (self.cpyrootpointer.data)
          self.cpyrootpointer=self.cpyrootpointer.pointer

      def removeitem(self,item):
        self.item=item
        self.cpyrootpointerr=copy.deepcopy(self.rootpointer)
        curr=self.cpyrootpointerr
        while self.cpyrootpointerr is not None:
            if(self.cpyrootpointerr.data==item):
              self.cpyrootpointerr=curr.pointer
              break




linkedlist=Llist()
linkedlist.rootpointer=Node('A')
linkedlist.rootpointer.pointer=Node('B')
linkedlist.rootpointer.pointer.pointer=Node('C')

linkedlist.addlist('D')
linkedlist.Dispaylist()

linkedlist.addlist('E')
print('break')
linkedlist.Dispaylist()
linkedlist.removeitem('E')
linkedlist.Dispaylist()

我在列表中有E-> D ---> A-> B-> C。调用removeitem()函数后,我想要的是D ---> A-> B-> C,但是我又得到了E-> D ---> A-> B-> C

2 个答案:

答案 0 :(得分:1)

您没有更改根指针,而是要更改副本。 “ self.cpyrootpointerr = curr.pointer”应为“ self.rootpointer = curr.pointer”。请注意,这仅适用于删除列表中第一项的情况。

答案 1 :(得分:0)

请参阅此post

中的删除功能
class LinkedList(Node):
    ...
    def delete(self,value):
        temp = self.__head
        while temp!=None:
            if temp.value == value and temp == self.__head:
                self.__head = temp.ref
                del temp
                self.__count -= 1
                break
            elif temp.ref != None and temp.ref.value == value:
                temp_ref = temp.ref.ref
                del temp.ref
                self.__count -= 1
                temp.ref = temp_ref
                break
            temp = temp.ref

相关问题