How can I create a linked list in Python?

Dongsheng Ruan rds1226 at sh163.net
Tue Jan 16 15:07:16 EST 2007


Thanks for your kindly help.
I am new CS student taking datat structure and algorithms with AHO's book 
with the same title.

The book is done in Pascal, which might be an outdated language.

However, my instructor probably wants us to understand the list ADT better 
by not using the built in list in Python.





"Gary Herron" <gherron at islandtraining.com> wrote in message 
news:mailman.2791.1168975031.32031.python-list at python.org...
> Dongsheng Ruan wrote:
>> with a cell class like this:
>>
>> #!/usr/bin/python
>>
>> import sys
>>
>> class Cell:
>>
>>  def __init__( self, data, next=None ):
>>   self.data = data
>>   self.next = next
>>
>>  def __str__( self ):
>>   return str( self.data )
>>
>>  def echo( self ):
>>   print self.__str__()
> If you really want a list (as Python defines a list - with all the 
> methods) then you should use Python's lists.  They are quite efficient and 
> convenient:
>
> l = [Cell(1), Cell(2), Cell(3)]
>
> However, if what you want is each cell to refer to a next cell (which 
> after all is what a linked list does), then you already have it with the 
> next attribute.  (In other languages you might implement 'next' as a 
> pointer, while in Python we call it a reference -- but it amounts to the 
> same thing.)  Create it this way:
>
> c = Cell(3)
> b = Cell(2, c) a = Cell(1, b)
>
> or
>
> a = Cell(1, Cell(2, Cell(3)))
>
> However, I'll repeat this:  The concept of a linked list if a figment of 
> languages with pointer data types.  Python abstracts that by allowing 
> attributes to contain references to other objects.  However, you're much 
> better off if you can use Python's list data structure rather than try to 
> emulate an outdated concept in a modern language.
>
> Gary Herron
>
>
> 





More information about the Python-list mailing list