how to print in reverse using data structure

can somebody help me how to print in reverse the data in a structure. i tried to pass the 1st, 2nd and so on node on tempPtr to reach the end (NULL) but when i was there i dont know how to get the data in the previous node so that it will print at the back.
you can use recursion or make another container ( a stack is nice ) and print that container out.
im using linked list. i just want to know how to make it using linked list
insert each element to the beginning of a new list, then print out the new list
can i have an example of the code
You will get better help when you post code that shows that you have tried. You don't have to post all of your code, perhaps just the reverse function.
use a recursion:

write a function that gets the node as a parameter.
call that function with the first node.
within the function:
if you have a next node call this function with the next node as parameter, otherwise print out the desired value.

that's it
As you're using a linked list, think of that: there's no reason why linked lists have to be unidirectional. You could make each node a chunk of data and two pointers, one to the next and one to the previous element.
Last edited on
If you have a single linked list, you use recursion as people sugested.
the function wil check if the "Next" pointer of the node is null, if it's not it will call the same function again with the "Next" pointer.
Hope it helps.
HERE is my reverse code.. i am really out of idea now.. i tried everyhting but it will loop forever... :(

can i have some corrections of my code? tnx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void reverse(ListNodePtr currentPtr)
{
   ListNodePtr newPtr, tempPtr;
   int i, j;
   if(currentPtr==NULL)
      printf("List is empty.\n\n");
   else
   {
      printf("The list is:\n");
      while(currentPtr!=NULL)
      {
	 for(i=0; i<counter; i++)
	 {
	    tempPtr=currentPtr->nextPtr;
	    if(tempPtr==NULL)
	    {
	       for(j=counter; j>0; j--)
	       {
		  newPtr=currentPtr->nextPtr;
		  printf("%c -->", newPtr->data);
	       }
	    }
	    printf("NULL\n\n");
	 }
      }
   }
}


i tried to walk until the null or the last value and then i try to print the data from the last. my problem is i don't know how to print it
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
void reverse(ListNodePtr currentPtr)
{
   if(currentPtr==NULL) {
      puts("List is empty\n");
      return;
   }
   else if ( currentPtr->nextPtr != null ) {
   	reverse(currentPtr->nextPtr);
   }
   else puts("End of list reached, now printing from last element to first\n")
   printf("%c -->", currentPtr->data);
}
THANKS SMAC!! it really helps
Topic archived. No new replies allowed.