Solved

Please Help...C++ : How to make a singly linked list print in reverse, recursively

Posted on 2004-04-25
6
315 Views
Last Modified: 2008-02-26
Sorry for posting in this in the wrong forum before...

Hi,

I've succesfully created a Queue with a singly linked list and have no problem with writing a function to print out the result in order, but I need to print out the list in reverse order, preferably recursively.  Here is my code.  Thanks in advance.

struct Node{
  int key;
  Node *next;
};

void printInReverse(Node * Head);   //function prototype to print in reverse

int main(){
  Node *header = new Node;
  header->next = NULL;
  Node *back = header;
 int x;  //variable displaying dequeue value
 
 

  for (int i =1; i < 10 ; i ++){   //loop to populate enqueue

  Node * newPtr = new Node;
  newPtr->key = i;
  newPtr->next = NULL;

  if ((header->next == NULL)&&(back == header))
     {
     ((header == 0) && (back == 0))
     header = back = newPtr;
     header->next = back;
     newPtr = 0;
     }
   
  else if((header->next!=NULL) || (back != header))
     //header = back;
       {
       back->next = newPtr;
       back = newPtr;
       newPtr = 0;
              }
     }
// ******END list population*********

// ******BEGIN dequeue *********
     
Node *tmpPtr = new Node;
     tmpPtr = header;

     if (header == back)
       header = back = 0;  //Queue is empty
     if (header != back)
       header = header->next; // header moves to second position

     x = tmpPtr->key;
     tmpPtr = 0;

// ******END dequeue function psuedocode *********

     //more testing ..................................
     cout << x << "= int x" << endl << endl;
     //END testing ...................................


     */
 
         
  printInReverse(header);   // call function to print list in reverse
     
system("pause");
return 0;
  }
// function currently prints in order, not reverse.  Please Help!

// ******BEGIN function to print in reverse*********
void printInReverse(Node *Head)   // this
  {
  if (Head == 0){
       cout << "List is empty." << endl;
       }
    //int count = 0;
     Node *printPtr = new Node;
     
     printPtr = Head;

     while(printPtr != 0)
       {
       
       cout << printPtr->key << endl;
       printPtr = printPtr->next; //advance pointer to next location in list...
       }
 }


// ******END function to print in reverse*********
0
Comment
Question by:r3r
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 5

Accepted Solution

by:
dennis_george earned 500 total points
ID: 10915620
Hi,

You are simply printing the data.... you should recursion

I think the following will do it for you..

void printInReverse(Node *Head)   // this
{
      if ( Head == NULL )
      {
            return ;
      } else {
            printInReverse( Head->next ) ;
      }

      printf(" %d  ::", Head->key) ;
}

Dennis
0
 

Author Comment

by:r3r
ID: 10915704
Thanks man, that's awesome.  Works great.  One more question...
Can you explain the last line..

printf(" %d  ::", Head->key) ;

specifically the " %d " part.  The Head->key argument is obvious.  I'm really new to this stuff (like you didn't know that already!!)

Thanks again.. you get 500 big ones!
0
 
LVL 5

Expert Comment

by:dennis_george
ID: 10915716
I think there is many programatic and logical flaw in your code.... I corrected those ... please read the comments I have written in between the code.....

Note :: Never never jump into coding before you design what you want to do.... First take a pen and paper draw diagrams and/or rough algo so that you are clear what and how will you acheive your goal.....

e.g.

Head ---->[]-->[]-->[]-->[]-->[]-->[]-->NULL

Now you want to print it reverse way.....
So check how will you do.... to print it reverse First you have to go at the end then go back....
So devise a method that how will you go at the end and also how will you come back......

Making a software or a program is not how you code but rather how you design and how you provide the solution.

//////////////////////// Your code ///////////////////////////////////////////
struct Node{
  int key;
  Node *next;
};

void printInReverse(Node * Head);   //function prototype to print in reverse

int main()
{
//  Node *header = new Node; // It should not be assigned memory at this stage
      Node *header = NULL;
//  header->next = NULL;
   Node *back = NULL ;
 
//  int x;  //variable displaying dequeue value
 
  for (int i = 1; i < 10 ; i ++){   //loop to populate enqueue
 
        Node * newPtr = new Node;
        newPtr->key = i;
        newPtr->next = NULL;

        if( header == NULL) {              
              header = back = newPtr;       
        } else {              
              back->next = newPtr;
              back = newPtr;
              newPtr = NULL;
        }
  }

// ******END list population*********

// ******BEGIN dequeue *********
     

//  Node *tmpPtr = new Node;  // Never Do this :: Here you are allocating memory for tmpPtr
//  tmpPtr = header;  // And here you are pointing your tmpPtr to header
                              // And Hence earlier memory allocated for tmpPtr is lost...
                              // i.e you cannot free that memory (Memory Leak)

//   Node *tmpPtr = header ;

//     if (header == back)
//       header = back = 0;  //Queue is empty
//     if (header != back)
//       header = header->next; // header moves to second position

//     x = tmpPtr->key;
//     tmpPtr = 0;

// ******END dequeue function psuedocode *********

     //more testing ..................................
//     cout << x << "= int x" << endl << endl;
     //END testing ...................................


         
  printInReverse(header);   // call function to print list in reverse
  printf("\n") ;

  system("pause") ;
 
  return 0;
}
// function currently prints in order, not reverse.  Please Help!

// ******BEGIN function to print in reverse*********

void printInReverse(Node *Head)   // this
{
      if ( Head == NULL )
      {
            return ;
      } else {
            printInReverse( Head->next ) ;
      }

      printf(" %d  ::", Head->key) ;
}


Dennis
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 5

Expert Comment

by:dennis_george
ID: 10915731
Hi,

printf(" %d  ::", Head->key) ;

is similar to

cout << Head->key ;

printf is a function defined in stdio.h // used in C
and cout is used in c++ // defined in iostream.h

Dennis
0
 

Author Comment

by:r3r
ID: 10915775
Thanks again...some of the code was preformated and I couldn't change it, but I don't doubt there is a lot of sloppy logic going on...  I'll study your notes and corrections.  And yes, I have been having problems with memory leaks as well.  
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10916296
Hi r3r,
> print out the list in reverse order, preferably recursively
Smells like what one would do in functional programming :-)

Be aware that the length of a list you can print this way is very limited, since your recursive function needs stack for each recursion.
recursion.

Cheers,
Stefan
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mixing C++ & C# in Vis Studio 2013 7 271
C++ to C# code conversion issue 4 126
Unresolved External Symbols 3 151
I could not set window to top 4 59
Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question