Recursive Algorithm: Printing in reverse order a Sorted Linked List

Discussion

Suppose we have a Sorted Linked List represented by the following structures:
struct  NodeType
{
	int  info ;
	NodeType*  next ;
}

class  SortedType 
{
public :
	
       .  .  .	// member function prototypes


private :

   NodeType*  listData  ;
           
} ;	



Suppose we have:
And we want to print out the sorted linked list in the
reverse order using the function:

RevPrint(listData);       




base case

If remaining list has 0 elements, there is no more processing to do.

general case

Print First Element;
listData = listData less first element

RevPrint(listData);
       

Solution

void   RevPrint ( NodeType*  listPtr )

//  Pre: listPtr points to an element of a list.
//  Post:  all elements of list pointed to by listPtr 
//  have been printed out in reverse order.
{  
   if  ( listPtr != NULL )	   // general case	
   {
	   RevPrint ( listPtr-> next ) ;  //process the rest
	   std::cout << listPtr->info << std::endl ;  
						// print this element
	 } 
	// Base case : if the list is empty, do nothing
}

 


 

 

 

© Lynne Grewe