在 Python 中实现链表

Implementing Linked List in Python

我试图在 Python 中实施 linked 列表进行练习,但我卡在了一个点上。我已经能够编写代码来添加和遍历列表,但在从列表中删除元素时遇到了麻烦。

我正在尝试删除用户在 remove () 中传递的元素

   class  node (object):
    def __init__ (self,data):
        self.data = data
        self.next = None
class lk (object):
    def __init__ (self):
        self.current_data = None
        self.header = None
    def add (self,data):
        New_node = node (data)
        New_node.next = self.current_data
        self.current_data = New_node
        self.head = self.current_data
    def display (self):
        #print 'coming to display', self.current_data
        self.current_data = self.head
        while (self.current_data is not None):
            print self.current_data.data
            self.current_data = self.current_data.next
    def remove (self,value):
        self.value = value
        present_node = self.head
        self.current_data = self.head

        while self.current_data is not None:
            if self.head == self.value:
                self.head = self.head.next
            else:
                #k = self.current_data.next
                #print k.data
                print self.current_data.data
                print self.current_data.next

            self.current_data = self.current_data.next

k = lk()
k.add (3)
k.add(4)
k.add(5)
k.display()
k.remove(4)
k.display

在 remove 方法中,我试图访问下一个节点的数据,使用 self.current.next.data 会出错,但我能够访问下一个 link 的地址,可能有人请尝试解释我哪里出错了以及如何纠正它。

我可以在您的代码中发现一些问题 -

  1. 这一行 - self.value = value - 在 remove() 方法中,为什么?为什么它在那里?您不需要将要删除的值作为实例变量添加到链表中,也不应该这样做。只需在函数内部以 value 完全访问它即可。

  2. 其次,为什么你的所有功能都在不断改变self.current_data?您不需要在 display()remove() 中更改它,您应该定义一个局部变量,例如 current_node` 并使用它。

  3. 其次,你的移除逻辑是错误的,目前你找到节点时,只是将head指向current_node,那是不可能的你想要什么。您想循环直到发现下一个数据包含您要查找的数据,然后将当前的下一个更改为指向下一个。

固定码-

class  node (object):
    def __init__ (self,data):
        self.data = data
        self.next = None

class lk (object):
    def __init__ (self):
        self.current_data = None
        self.header = None
    def add (self,data):
        New_node = node(data)
        New_node.next = self.current_data
        self.current_data = New_node
        self.head = self.current_data
    def display (self):
        #print 'coming to display', self.current_data
        current_node = self.head
        while (current_node is not None):
            print(current_node.data)
            current_node = current_node.next
    def remove (self,value):
        current_node = self.head
        if current_node.data == value:
            self.head = current_node.next
            return
        while current_node.next is not None:
            if current_node.next.data == value:
                current_node.next = current_node.next.next
                break

            current_node = current_node.next

k = lk()
k.add (3)
k.add(4)
k.add(5)
k.display()
k.remove(4)
print("Hmm")
k.display()