0

I am playing with linked lists for the first time, and I can't seem to understand why my add method isn't working.

Here is my code:

    class Node(object):

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

        def getData(self):
            return self.data

        def getNext(self):
            return self.next

        def setData(self, newdata):
            self.data = newdata

        def setNext(self, newnext):
            self.data = newnext




    class UnorderedList(object): # also known as linked list

        def __init__(self):
            self.head = None

        def isEmpty(self):
            return self.head == None

        def add(self, item):
            temp = Node(item)
            temp.setNext(self.head)
            self.head = temp

        def size(self):
            current = self.head
            count = 0
            while current != None:
                count = count + 1
                current = current.getNext()
            return count

        def search(self, item):
            current = self.head
            found = False
            while current != None and not found:
                if current.getData == item:
                    found = True
                else:
                    current = current.getNext()
            return found

mylist = UnorderedList()

print mylist.size()
mylist.add(6)
print mylist.size()
mylist.add(9)
print mylist.size()

But I am not getting the desired outcome, this is what my terminal is displaying:

$ python linkedlist.py
0
1
1

The add method seems to not be working, but I can't figure out why. For reference, I have been using this to learn.

1 Answer 1

1

Replace:

   def setNext(self, newnext):
        self.data = newnext

with:

   def setNext(self, newnext):
        self.next = newnext
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.