Recursively traverse linked list -- help!

O Polite ol1 at v10a.com
Tue Feb 19 03:16:38 EST 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? 
  

thanks 

Bob at kontactNOspamPLEASE.com -- 

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:
            new.next = self.start
        self.start = new

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

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

    def __str__(self):
        return str(self.data)
    

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

    for i in range(10):
        mylist.push(i)
        
    for i in range(11):
        print mylist
        mylist.pop()



http://mail.python.org/mailman/listinfo/python-list






More information about the Python-list mailing list