如何从链表中删除节点?

时间:2014-05-13 19:59:14

标签: python class oop error-handling linked-list

作为OOP上的第一个项目,我正在处理链表oop类,完成了大部分方法,但删除节点方法不起作用。 当我运行代码时,我收到此错误:

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 

1 个答案:

答案 0 :(得分:2)

您的Node类在value方法中分配了属性__init__,但没有在属性val中分配,因此出现错误。混淆可能来自于您传递给__init__的变量称为val