How can I implement a linked list like the implementations in c with struct-s and arrays (or pointers). to simbolize the working principe
Gary Herron je napisao/la: > 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 -- http://mail.python.org/mailman/listinfo/python-list