Function showing list in reverse order

Asked

Viewed 361 times

-1

def imprimeDeTrasParaFrente(lista):
    if lista == None :
       return
    imprimeDeTrasParaFrente(lista.proximo)
    print lista,

class Node(object):

   def __init__(self, carga=None, proximo=None):
       self.carga = carga
       self.proximo = proximo

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

   no1, no2, no3 = Node(1), Node(2), Node(3)
   no1.proximo, no2.proximo = no2, no3

   imprimeDeTrasParaFrente(no1)

With the function printDeTrasParaFrente() I was able to print the list elements in reverse order, and it only checks whether the list is empty and calls itself with the next node in the list. In my perspective the print function is never called because when the list is empty the function simply returns and ends the program, or I’m wrong?

1 answer

0


There is nothing wrong with the logic of your program, it works exactly as you described it: it displays the values contained in the nodes of a chained list iterating from the last node toward the first.

What’s making it not work is the indentation of the blocks, which is something crucial in Python.

For everything to work perfectly, watch out for code indentation:

inserir a descrição da imagem aqui

Reference Wikibooks

  • I was able to understand the logic now, recursive functions call themselves within the function, the Return command is terminating the function within the function’s own scope that means the program flow goes back to the scope of the main function so it would be possible to add one more Return to the end of the print function so recursive functions can contain two Return but at the end return only one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.