0

I'm trying to create a function that removes duplicate nodes from a link-list. My issue is that I'm a problem every time I call remove_node it returns 'NameError: name 'remove_node' is not defined' I don't know maybe if I wrote my class wrong??

I also hope my logic to remove duplicate is correct. Thank for your help!

class Node:
    #Singly link list
    def __init__(self,data):
        self.data = data
        self.next = None

class linklist:
    #linkList class
    def __init__(self):
        self.head = None

    def push(self,data):
        node = Node(data)# create a new node

        if self.head == None: 
         #check to see if the head node is empty
            self.head = node # If its empty add it to the new node
            return
        #if the head of the linklist is filled

        current = self.head
        while current.next is not None:
        #Check the current postion is empty
        #Move to the next line if nothing is there
            current = current.next

        current.next = node #point self.head to a new node




    def lenght(self):
        #note the count doesn't start at zero
        cur = self.head
        counter = 0
        while cur is not None:
            counter+=1
            cur = cur.next
        print('Linklist len: '+str(counter))

    def printList(self):
        curr = self.head
        elem = []

        while(curr != None):
            elem.append(curr.data)
            curr = curr.next
        print(elem)
    #1->2->3
    def remove_node(self,data):
        #1->2->3
        curr = self.head
        if curr is not None and curr.data == data:
            self.head = curr.next
            curr = None
        #look for the node that has the data we are looking for
        while curr is not None:
            if curr.data == data:
                break
            prev = curr
            curr = curr.next

        #if data isn't found just reutrn
        if(curr == None):
            return

        #allow us to unlink the nodes
        prev.next = curr.next
        curr = None

    def remove_dups(self):
        p1 = self.head
        p2 = p1.next
        while p1 is not None:
            data = p1.data
            p2 = p1.next
            while p2 is not None:
                if p2.data == data:
                    remove_node(p2.data)
                p2 = p2.next
                print("hello")
            p1 = p1.next





#Testing to see if my class works
llist = linklist()
llist.push(1)
llist.push(2)
llist.push(1)
llist.push(3)
llist.push(1)
llist.printList()
llist.lenght()
#Testing 1->2->1->3->1 result should only be 1->2->3
llist.remove_dups()
llist.printList()
  • 1
    `remove_node` is a method of your class. You need to call it within the class itself using `self.remove_node`. – Sheldore Jan 01 '19 at 20:22
  • You should read [this](https://stackoverflow.com/questions/5615648/python-call-function-within-class) – Sheldore Jan 01 '19 at 20:23

0 Answers0