Python circular linked list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Joseph Guildino
    New Member
    • Dec 2010
    • 1

    Python circular linked list

    Good afternoon all!

    I have this program in Python that is really starting to make my head go crazy. It utilizes linked lists (circularly linked list).

    Now, correct me if I am wrong, but a circular linked list works like this: (the number on the left represents the number of lists)
    o - (Header is empty class)

    1 - header.next = first element (call this EL1)
    EL1.next = EL1

    2 - header.next = first element (call this EL1)
    EL1.next = second element (call this EL2)
    EL2.next = EL1

    3 - header.next = first element (call this EL1)
    EL1.next = third element (call this EL3)
    EL3.next = second element (call this EL2)
    EL2.next = EL1

    I believe that is the right definition of circular list.
    Note that the header will have the next element and also the size of the array.

    Currently, I am having some problems and I will show you the code and the results.

    Let me define some classes and functions, first.

    class list:
    holds the objects header and size
    initially sets the header to empty node
    initially sets size to 0

    class emptynode:
    holds no objects, it is empty

    class node:
    holds the value of the element
    holds the next object

    A function I created was:
    Code:
    def addin(data, list):
        new = Node(data, EmptyNode())
        list.size += 1
    
        if isinstance(list.head, EmptyNode):
            list.head = newNode
            
        elif isinstance(list.head, Node):
            temporary = list.head.next
            new.next = temporary
            list.head.next = new
    Where it takes a value and adds it to the circular list by definition seen earlier.

    Works wonderfully, EXCEPT, say we have the following commands:
    Code:
    l = list()
    addin('A', l)
    addin('B', l)
    addin('C', l)
    We get the following memory allocations returned:

    Code:
    ('0', 'A', <__main__.Node object at 0x022953D0>, <__main__.Node object at 0x02295430>)
    
    ('1', 'C', <__main__.Node object at 0x02295430>, <__main__.Node object at 0x02295410>)
    
    ('2', 'B', <__main__.Node object at 0x02295410>, <__main__.EmptyNode object at 0x004614C8>)
    The first memory allocation represents the current element. For instance, <__main__.Nod e object at 0x022953D0> is the memory allocation of A element. The second memory allocation represents the next element. So you see <__main__.Nod e object at 0x02295430> is the same as C (because C is the next node of A).

    All works great until we get to the last element (in this case B). B points to the original header (before any adding was done). Now, B's next should point to the memory allocation of A... but it does not.

    Can someone please help me with this algorithm

    Thank you in advance!!
Working...