1

I am stuck implementing the add function of a circularly linked list in python. I have a head pointer that should be a reference to a node, but every time I add something to the list, head is always None. Here is the code I have so far:

class CircleList():

    __slots__ = ('head', 'size')

    def __init__(self):
        self.head = None
        self.size = 0

    def __str__(self):
        result = "<"
        node = self.head
        count = self.size
        while count != 0:
            result = result + str(node.data)
            if count != 1:
                result = result + ", "
            node = node.next
            count -= 1
        result = result + ">"
        return result

    def add(self, element):
        head = self.head
        print(head)
        size = self.size
        if head == None:
            head = Node(element, None)
            head.next = head
        else:
            cursor = head
            while cursor.next != head:
                cursor = cursor.next
            temp = Node(element, head)
            cursor.next = temp
        size += 1


class Node():
    __slots__ = ('data','next')

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

Here is the driver:

stream = open('data.txt', 'r')

circlelist = CircleList()

for name in stream
    circlelist.add(name)

print(circlelist)
1
  • 1
    Any reason why you implement it like this? It's not exactly pythonic, and you could easily come up with a much more elegant version extending list, providing meta-methods like __getitem__ etc. and using indices. This also eliminates the need for the superfluous Node class. Also, I suggest sticking to the well-known interface of list. Commented Dec 5, 2010 at 17:23

2 Answers 2

1

You only assigning the new node to your local head variable in your add() method, not to the actual CircleList instance member.

You might want to do something like:

def add(self, element):
    head = self.head
    print(head)
    size = self.size
    if head is None:
        self.head = head = Node(element, None)  # Also set the instance member.
        head.next = head
Sign up to request clarification or add additional context in comments.

Comments

0

Easy to fix! In your add function, you assign the new head to the head variable -- which is restricted to the scope of the function, and will dissapear when it returns!

You have to set the value of self.head, the attribute of the current instance.

Edit: when you assign head = self.head you are making them both point to the same object. But they are separate references: whether they happen to reference the same thing or not, changing one won't change the other.

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.