user3290553
user3290553

Reputation: 87

NoneType Error: Python Doubly Linked List

Getting caught up in a solution to NoneType errors stemming from using my functions add and append in the below code to an empty Double_list class object. Best way to avoid?

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

Upvotes: 0

Views: 586

Answers (2)

Peter Gibson
Peter Gibson

Reputation: 19554

You're initialising head and tail to None, but then trying to set prev and next members on them when inserting the first 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

You should check for this case

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

An alternate solution is to start with "dummy" nodes for the head and tail:

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

And then insert items in between these nodes

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

Although I find this tends to needlessly complicate things a bit.

Upvotes: 1

James Mills
James Mills

Reputation: 19040

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

This will always raise a NoneType exception because self.tail is initially None then you assign a reference to it (None) to temp and try to assign something to None. Won't work.

YOu need to probably firstly assign a new object reference to self.tail

Upvotes: 0

Related Questions