开发者

circularly linked list in python

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 开发者_JS百科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)


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜