Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse Linked-Lists Python

I am trying to figure out how I can traverse linked list in Python using Recursion.

I know how to traverse linked-lists using common loops such as:

 item_cur = my_linked_list.first
       while item_cur is not None:
           print(item_cur.item)
           item_cur = item_cur.next  

I was wondering how I could turn this loop into a recursive step.

Thanks

like image 792
Andre Avatar asked Oct 18 '14 23:10

Andre


1 Answers

You could do something like this:

def print_linked_list(item):
    # base case
    if item == None:
        return
    # lets print the current node 
    print(item.item)
    # print the next nodes
    print_linked_list(item.next)
like image 145
avi Avatar answered Sep 29 '22 11:09

avi