Griffin
Griffin

Reputation: 305

Python Linked lists AttributeError: 'NoneType' object has no attribute 'next'

I'm trying to write a program to delete duplicate values from a linked list

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


class LinkedList(object):
    def __init__(self):
        self.head = None

    def append(self, data):
        node = self.head
        if(node == None):
            self.head = Node(data)
            return
        while(node.next):
            node = node.next
        node.next = Node(data)
        return

def removeDups(ll):
    if(ll.head is None):
        return
    headNode = ll.head
    while(headNode):
        lead = headNode
        while(lead.next):
            if(lead.next.data == headNode.data):
                lead.next = lead.next.next
            lead = lead.next
        headnode = headNode.next
    return

list = LinkedList()

list.append(1)
list.append(2)
list.append(3)
list.append(1)

removeDups(list)

The error points to the line at "while(lead.next):" with the Arribute Error 'NoneType' object has no attribute 'next'

Am I not able to assign two values to the same listnode? Are headNode and lead pointers?

Upvotes: 1

Views: 1279

Answers (1)

jawad-khan
jawad-khan

Reputation: 313

This should work for you. You need two changes in your removeDups function:

def removeDups(ll):
    if(ll.head is None):
        return
    headNode = ll.head
    while(headNode):
        lead = headNode
        while(lead and lead.next):
            if(lead.next.data == headNode.data):
                lead.next = lead.next.next
            lead = lead.next
        headNode = headNode.next
    return

Upvotes: 1

Related Questions