如何从链表中删除一个节点



作为面向对象的第一个项目,我正在研究一个链表面向对象类,完成了大多数方法,但删除节点方法不起作用。当我运行代码时,我得到这个错误:

AttributeError: 'Node'对象没有属性'val'

我不知道我做错了什么!

class Node():
    def __init__(self, val):
        self.value = val
        self.next = None

class Linked_list():
    def __init__(self):
        self.next = None
        nextnode=self.next

    def insert(self, val, loc):
        p = self
        for i in range(0, loc):
            p = p.next
        tmp = p.next
        newNode = Node(val)
        p.next = newNode
        newNode.next = tmp
    def find(self, val):
        p = self.next
        # loc = 0     # in case we want to return the location
        while p != None:
            if p.value == val:
                return p
            else:
                p = p.next
                #loc=loc+1   # in case we want to return the location
        return None
    def remove_node(self, node):
        current = self.next
        previous = None
        found = False
        while not found:
                if current.val == node:
                    found = True
                else:
                    previous = current
                    current = current.next
        if previous == None:
            self.next = current.next
        else:
            previous.current.next

    def __eq__(self, other):
        cnt=0
        s=self.next
        p=other.next
        if Linked_list.length(self)!=Linked_list.length(other):
            return False
        if s.value==p.value:
            for i in range(Linked_list.length(self)-1):
                p=p.next
                s=s.next
                if s.value==p.value:
                    cnt+=1
        if cnt==Linked_list.length(self)-1:
            return True
        else:
            return False 

您的Node类具有在__init__方法中分配的属性value,但不是属性val,因此出现错误。这种混淆可能是因为您传递给__init__的变量称为val

相关内容

  • 没有找到相关文章

最新更新