NoneType错误:Python双链表

时间:2014-05-20 00:31:08

标签: python linked-list nonetype

陷入使用我的函数产生的NoneType错误的解决方案中添加并将下面的代码附加到空的Double_list类对象中。最好的避免方式?

class Dbl_Node:

    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None

class Double_list:

    def __init__(self): # Creates initial list w/ head and tail as None
        self.head = None
        self.tail = None

    def add(self, item): # adds node to beginning/head of list
        temp = self.head
        self.head = Dbl_Node(item)
        temp.prev = self.head
        self.head.next = temp

    def append(self, item): # adds node to end/tail of list
        temp = self.tail
        self.tail = Dbl_Node(item)
        self.tail.prev = temp
        temp.next = self.tail

2 个答案:

答案 0 :(得分:1)

您正在初始化headtailNone,但在插入第一个时尝试设置prevnext成员Dbl_Node

def add(self, item):
    temp = self.head # on the first call to "add", self.head is None
                     # (as set in __init__) so temp is now None

    self.head = Dbl_Node(item) # create a new node and assign it to self.head
                               # this is fine

    temp.prev = self.head # this says assign the new node in self.head to the "prev"
                          # member of temp, however temp is None so the temp.prev part
                          # throws the error

您应该检查此案例

def add(self, item): # adds node to beginning/head of list
    temp = self.head
    self.head = Dbl_Node(item)
    if temp is not None:
        temp.prev = self.head

另一种解决方案是以" dummy"头尾节点:

def __init__(self):
    self.head = Dbl_Node(None)
    self.tail = Dbl_Node(None)
    self.head.next = self.tail
    self.tail.prev = self.head

然后在这些节点之间插入项目

def add(self, item):
    temp = self.head.next
    self.head.next = Dbl_Node(item)
    temp.prev = self.head.next
    self.head.next.next = temp

虽然我发现这有点不必要地使事情复杂化。

答案 1 :(得分:0)

def append(self, item): # adds node to end/tail of list
        temp = self.tail
        self.tail = Dbl_Node(item)
        self.tail.prev = temp
        temp.next = self.tail

这将始终引发NoneType例外,因为 self.tail最初为None,然后您指定了引用 到它(None)到temp并尝试分配一些内容 None。不会工作。

你可能首先需要为self.tail

分配一个新的对象引用