Recursively traverse linked list -- help!

O Polite ol1 at
Tue Feb 19 09:16:38 CET 2002

On Tue, 2002-02-19 at 03:16, bob wrote:

Hello -- I searched the archives to no avail. 

Does anyone have a python code snippet showing how to recursively
traverse a linked list? 


Bob at -- 

Well, first you'd want to have a way of representing a linked list.
Here's one straighforward way of doing it, but unless your taking
Datastructures 101 you'll never be interested in it. The builtin list
type will always be faster than anything you implement in python, and
now in python2.2 you can subclass the builtin types as any other class.

class LinkedList:
    def __init__(self):
        self.start = None
    def push(self, value = None):
        new = ListElement(value)
        if self.start:
   = self.start
        self.start = new

    def pop(self):
        result = None
        if self.start:
            result =
            self.start =
        return result
    def __str__(self):
        result = ""
        current = self.start
        while current:
            result += "%s " % (str(current))
            current =
        return result

class ListElement:
    def __init__(self, value = None): = value = None

    def __str__(self):
        return str(

if __name__ == '__main__':
    mylist = LinkedList()

    for i in range(10):
    for i in range(11):
        print mylist

More information about the Python-list mailing list