faqts : Computers : Programming : Languages : Python : Common Problems : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 16 people (69%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

I'm searching information regarding the use of pointers for linked and double linked lists.

Jun 15th, 2000 05:09
unknown unknown, Martijn Faassen


Linked lists aren't hard:

class Node:
    def __init__(self, next):
        self.next = next

linked_list = Node(Node(Node()))

Every name in Python's a reference, so no pointers are needed. Just 
think of every name in Python as a pointer (to an object), if you like.

Doubly linked lists are along the same pattern, but have the trouble 
that they introduce circular references, which is bad for Python's 
reference counting based garbage collection scheme. You have to break 
one of the references yourself for it to work:

class Node:
    def __init__(self, prev, next):
        self.prev = prev
        self.next = next

node1 = Node(None, None)
node2 = Node(None, None)
node1.next = node2
node2.prev = node1

# and now to clean up so that refcounting works:
node2.prev = None