function to print linked list in reverse order












2















I was searching on how can I print a reverse of linked list and I found this piece of code



/* Function to reverse the linked list */
void printReverse(struct node* head)
{
// Base case
if (head == NULL)
return;

// print the list after head node
printReverse(head->next);

// After everything else is printed, print head
printf("%d ", head->data);
}


The problem is that I do not understand the part where it reaches the last pointer which points to NULL and how it comes back one by one and prints the linked list in reverse order.



Is the return statement what makes it go step by step back? Or something else? Please help because I do not understand.










share|improve this question

























  • You need to look into how recursion works.

    – Michael Albers
    Jan 1 '17 at 0:42






  • 1





    There's an implicit return; immediately before the } at the end of the function. After the data is printed, the function returns. In the case when the node is NULL, it returns without printing anything, of course.

    – Jonathan Leffler
    Jan 1 '17 at 3:14











  • A LIFO structured linked list might work.

    – RoadRunner
    Jan 1 '17 at 3:37
















2















I was searching on how can I print a reverse of linked list and I found this piece of code



/* Function to reverse the linked list */
void printReverse(struct node* head)
{
// Base case
if (head == NULL)
return;

// print the list after head node
printReverse(head->next);

// After everything else is printed, print head
printf("%d ", head->data);
}


The problem is that I do not understand the part where it reaches the last pointer which points to NULL and how it comes back one by one and prints the linked list in reverse order.



Is the return statement what makes it go step by step back? Or something else? Please help because I do not understand.










share|improve this question

























  • You need to look into how recursion works.

    – Michael Albers
    Jan 1 '17 at 0:42






  • 1





    There's an implicit return; immediately before the } at the end of the function. After the data is printed, the function returns. In the case when the node is NULL, it returns without printing anything, of course.

    – Jonathan Leffler
    Jan 1 '17 at 3:14











  • A LIFO structured linked list might work.

    – RoadRunner
    Jan 1 '17 at 3:37














2












2








2








I was searching on how can I print a reverse of linked list and I found this piece of code



/* Function to reverse the linked list */
void printReverse(struct node* head)
{
// Base case
if (head == NULL)
return;

// print the list after head node
printReverse(head->next);

// After everything else is printed, print head
printf("%d ", head->data);
}


The problem is that I do not understand the part where it reaches the last pointer which points to NULL and how it comes back one by one and prints the linked list in reverse order.



Is the return statement what makes it go step by step back? Or something else? Please help because I do not understand.










share|improve this question
















I was searching on how can I print a reverse of linked list and I found this piece of code



/* Function to reverse the linked list */
void printReverse(struct node* head)
{
// Base case
if (head == NULL)
return;

// print the list after head node
printReverse(head->next);

// After everything else is printed, print head
printf("%d ", head->data);
}


The problem is that I do not understand the part where it reaches the last pointer which points to NULL and how it comes back one by one and prints the linked list in reverse order.



Is the return statement what makes it go step by step back? Or something else? Please help because I do not understand.







c struct linked-list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 1 '17 at 0:45









Michael Albers

3,26831626




3,26831626










asked Jan 1 '17 at 0:39









ShehabAldeenShehabAldeen

154




154













  • You need to look into how recursion works.

    – Michael Albers
    Jan 1 '17 at 0:42






  • 1





    There's an implicit return; immediately before the } at the end of the function. After the data is printed, the function returns. In the case when the node is NULL, it returns without printing anything, of course.

    – Jonathan Leffler
    Jan 1 '17 at 3:14











  • A LIFO structured linked list might work.

    – RoadRunner
    Jan 1 '17 at 3:37



















  • You need to look into how recursion works.

    – Michael Albers
    Jan 1 '17 at 0:42






  • 1





    There's an implicit return; immediately before the } at the end of the function. After the data is printed, the function returns. In the case when the node is NULL, it returns without printing anything, of course.

    – Jonathan Leffler
    Jan 1 '17 at 3:14











  • A LIFO structured linked list might work.

    – RoadRunner
    Jan 1 '17 at 3:37

















You need to look into how recursion works.

– Michael Albers
Jan 1 '17 at 0:42





You need to look into how recursion works.

– Michael Albers
Jan 1 '17 at 0:42




1




1





There's an implicit return; immediately before the } at the end of the function. After the data is printed, the function returns. In the case when the node is NULL, it returns without printing anything, of course.

– Jonathan Leffler
Jan 1 '17 at 3:14





There's an implicit return; immediately before the } at the end of the function. After the data is printed, the function returns. In the case when the node is NULL, it returns without printing anything, of course.

– Jonathan Leffler
Jan 1 '17 at 3:14













A LIFO structured linked list might work.

– RoadRunner
Jan 1 '17 at 3:37





A LIFO structured linked list might work.

– RoadRunner
Jan 1 '17 at 3:37












5 Answers
5






active

oldest

votes


















2














This is a recursive function. Recursive functions work by pushing variables onto the execution stack. The execution order pops off the stack in reverse order from the order it was pushed on the stack. This means that the last execution prints first, then the one previous to that, and so forth until all executions of printReverse print their values.






share|improve this answer
























  • ...and better to convert to tail recursion.

    – 0andriy
    Jan 1 '17 at 8:46





















0














This is a recursive function; that is to say, it calls itself.



Let's use the sequence example as your example data:



When you first run the function, it's pointing at the head, and the head is the item containing the data e. It has a next property, which is the item containing the data x. Therefore, head == NULL evaluates False and the if statement doesn't fire.



The function then calls a second copy of itself, pointing to the next item in the list - the item containing x. This has a next property, which is the item containing a. The function then calls a third copy of itself with this item, and so on and so forth until it hits the final e, and calls a copy of itself with the next property of that item - that is to say, it calls itself with NULL as the input.



This copy of the function then returns due to the if statement- crucially, it returns to the function that called it, in this case the copy of itself the level above. This copy then carries on where it left off, executing printf("%d ", head->data); - in this case, it prints an e. Then it falls out of the body of the function and so returns to the function that called it. This copy of the function will have a head->data value of l, and this will print as above. As such, it then runs through back up the chain until it gets to the original function call, prints the first e, and then returns to the function that called it.



Hope this makes sense, I know it's not the best or most elegant explanation of recursion but there's a lot of material out there if this is confusing explaining exactly how recursion works and how useful it can be!






share|improve this answer































    0














    The thing that makes it go in reverse is to have the printf() call after the recursive call to itself.



    You can try interchanging the two calls as in



    void printNormal(struct node* head)
    {
    // Base case
    if (head == NULL)
    return;

    // Before all, we print this node info.
    printf("%d ", head->data);

    // print the rest of the list after this node
    printReverse(head->next);

    }


    And you'll get the forward printing of the list.



    The mission of the so commented Base case is to avoid infinite recursion. The end of the list is special, we can do the check on entering the printReverse() function, so we can deal with the special case of an empty list, or we have to do it at each call (then we should put a check before calling the function inside it, and in the code that calls the recursive function (better to put it at the beginning).






    share|improve this answer































      0














      As others have already explained the recursive version. I suggest you to have a look at this iterative version of printing linked list in reverse order. This is more easy to understand and implement as compared to recursive version, however it increases time complexity.



          // To ease testing of code here linked list is created randomly of given size.
      #include<stdio.h>
      #include<cstdlib>
      #include<time.h>
      #define size 10 //Size of list
      struct node
      {
      int info;
      struct node * next;
      };
      typedef struct node* Node;
      Node start;
      int main()
      {
      int i;
      srand(time(NULL));
      for(i=0;i<size;i++)
      {
      Node ptr;
      ptr=(Node)malloc(sizeof(node));
      ptr->info=rand()%100; //random list is created of given size.
      ptr->next=NULL;
      if(start==NULL)
      start=ptr;
      else
      {
      ptr->next=start;
      start=ptr;
      }
      }
      printf(" Traversal of Linked List in forward direction -n");
      Node temp=start;
      while(temp!=NULL)
      {
      printf(" %d ",temp->info);
      temp=temp->next;
      }
      printf("n Traversal of Linked List in backward direction -n");
      Node ptr=NULL;
      while(ptr!=start)
      {
      temp=start;
      while(temp->next!=ptr)
      temp=temp->next;
      printf(" %d ",temp->info);
      ptr=temp;
      }
      return 0;
      }


      For more details visit-
      https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git






      share|improve this answer































        -1














        Jim Rodgers hits the nail on the head. However, you could make life very easy for yourself by having a doubly linked list.



        So for example your entry (node) has both a previous and next member pointing to the previous entry and next entry respectively. Then you don't need more "obfuscated" code than necessary.






        share|improve this answer
























        • This answer has nothing to do with the sense of the question. The SO wants to understand why it works that way and how to do in the opposite direction, and you are blaming about some programming customs that are far of being of interest here (or even useful).

          – Luis Colorado
          Jan 2 '17 at 10:48











        • LOL! So in the context of singly linked list (and its reversal), some friendly advice as to the use of the natural alternative, the doubly linked list, is of no use. BTW, when you need to reverse search or indeed swap entries in a linked list, the doubly linked data structure is the advised option in cases where memory is not severely limited. BTW, I like the way you think I was talking about a "custom" rather than a data structure.

          – cdcdcd
          Jan 2 '17 at 13:25













        • reLOL! the exercise was about recursive function calls, and not on double linked lists. I know a double linked list allows you to traverse it either direction, but the question was Is the return statement what makes it go step by step back? Or something else? and not what is the best linked list implementation to traverse it backwards?

          – Luis Colorado
          Jan 3 '17 at 12:17













        • Luis see first line of question: "I was searching on how can I print a reverse of linked list and I found this piece of code". The issue of reverse ordering was the focus of his original problem. The issue of recursion was a fallout of this original problem and led to the question. I was simply pointing him to a simpler solution if this approach is causing him some consternation. Personally, I find (from experience) more general answers give helpful leads. If it is not welcome I'll take it down.

          – cdcdcd
          Jan 3 '17 at 12:44











        • You are right in that complete general answers are better than simple or nongeneral ones. But recursion is a general technique that must be studied also, even not being many times the best approach to a problem. The first example in studying recursion is normally the factorial one, which no one solves by a recursive function in reality, and questions arise on that, but nobody answers it saying that recursion is something to be avoided. Not before having a good knowledge.

          – Luis Colorado
          Jan 4 '17 at 8:24











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41412592%2ffunction-to-print-linked-list-in-reverse-order%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        This is a recursive function. Recursive functions work by pushing variables onto the execution stack. The execution order pops off the stack in reverse order from the order it was pushed on the stack. This means that the last execution prints first, then the one previous to that, and so forth until all executions of printReverse print their values.






        share|improve this answer
























        • ...and better to convert to tail recursion.

          – 0andriy
          Jan 1 '17 at 8:46


















        2














        This is a recursive function. Recursive functions work by pushing variables onto the execution stack. The execution order pops off the stack in reverse order from the order it was pushed on the stack. This means that the last execution prints first, then the one previous to that, and so forth until all executions of printReverse print their values.






        share|improve this answer
























        • ...and better to convert to tail recursion.

          – 0andriy
          Jan 1 '17 at 8:46
















        2












        2








        2







        This is a recursive function. Recursive functions work by pushing variables onto the execution stack. The execution order pops off the stack in reverse order from the order it was pushed on the stack. This means that the last execution prints first, then the one previous to that, and so forth until all executions of printReverse print their values.






        share|improve this answer













        This is a recursive function. Recursive functions work by pushing variables onto the execution stack. The execution order pops off the stack in reverse order from the order it was pushed on the stack. This means that the last execution prints first, then the one previous to that, and so forth until all executions of printReverse print their values.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 1 '17 at 0:45









        Jim RogersJim Rogers

        1,211515




        1,211515













        • ...and better to convert to tail recursion.

          – 0andriy
          Jan 1 '17 at 8:46





















        • ...and better to convert to tail recursion.

          – 0andriy
          Jan 1 '17 at 8:46



















        ...and better to convert to tail recursion.

        – 0andriy
        Jan 1 '17 at 8:46







        ...and better to convert to tail recursion.

        – 0andriy
        Jan 1 '17 at 8:46















        0














        This is a recursive function; that is to say, it calls itself.



        Let's use the sequence example as your example data:



        When you first run the function, it's pointing at the head, and the head is the item containing the data e. It has a next property, which is the item containing the data x. Therefore, head == NULL evaluates False and the if statement doesn't fire.



        The function then calls a second copy of itself, pointing to the next item in the list - the item containing x. This has a next property, which is the item containing a. The function then calls a third copy of itself with this item, and so on and so forth until it hits the final e, and calls a copy of itself with the next property of that item - that is to say, it calls itself with NULL as the input.



        This copy of the function then returns due to the if statement- crucially, it returns to the function that called it, in this case the copy of itself the level above. This copy then carries on where it left off, executing printf("%d ", head->data); - in this case, it prints an e. Then it falls out of the body of the function and so returns to the function that called it. This copy of the function will have a head->data value of l, and this will print as above. As such, it then runs through back up the chain until it gets to the original function call, prints the first e, and then returns to the function that called it.



        Hope this makes sense, I know it's not the best or most elegant explanation of recursion but there's a lot of material out there if this is confusing explaining exactly how recursion works and how useful it can be!






        share|improve this answer




























          0














          This is a recursive function; that is to say, it calls itself.



          Let's use the sequence example as your example data:



          When you first run the function, it's pointing at the head, and the head is the item containing the data e. It has a next property, which is the item containing the data x. Therefore, head == NULL evaluates False and the if statement doesn't fire.



          The function then calls a second copy of itself, pointing to the next item in the list - the item containing x. This has a next property, which is the item containing a. The function then calls a third copy of itself with this item, and so on and so forth until it hits the final e, and calls a copy of itself with the next property of that item - that is to say, it calls itself with NULL as the input.



          This copy of the function then returns due to the if statement- crucially, it returns to the function that called it, in this case the copy of itself the level above. This copy then carries on where it left off, executing printf("%d ", head->data); - in this case, it prints an e. Then it falls out of the body of the function and so returns to the function that called it. This copy of the function will have a head->data value of l, and this will print as above. As such, it then runs through back up the chain until it gets to the original function call, prints the first e, and then returns to the function that called it.



          Hope this makes sense, I know it's not the best or most elegant explanation of recursion but there's a lot of material out there if this is confusing explaining exactly how recursion works and how useful it can be!






          share|improve this answer


























            0












            0








            0







            This is a recursive function; that is to say, it calls itself.



            Let's use the sequence example as your example data:



            When you first run the function, it's pointing at the head, and the head is the item containing the data e. It has a next property, which is the item containing the data x. Therefore, head == NULL evaluates False and the if statement doesn't fire.



            The function then calls a second copy of itself, pointing to the next item in the list - the item containing x. This has a next property, which is the item containing a. The function then calls a third copy of itself with this item, and so on and so forth until it hits the final e, and calls a copy of itself with the next property of that item - that is to say, it calls itself with NULL as the input.



            This copy of the function then returns due to the if statement- crucially, it returns to the function that called it, in this case the copy of itself the level above. This copy then carries on where it left off, executing printf("%d ", head->data); - in this case, it prints an e. Then it falls out of the body of the function and so returns to the function that called it. This copy of the function will have a head->data value of l, and this will print as above. As such, it then runs through back up the chain until it gets to the original function call, prints the first e, and then returns to the function that called it.



            Hope this makes sense, I know it's not the best or most elegant explanation of recursion but there's a lot of material out there if this is confusing explaining exactly how recursion works and how useful it can be!






            share|improve this answer













            This is a recursive function; that is to say, it calls itself.



            Let's use the sequence example as your example data:



            When you first run the function, it's pointing at the head, and the head is the item containing the data e. It has a next property, which is the item containing the data x. Therefore, head == NULL evaluates False and the if statement doesn't fire.



            The function then calls a second copy of itself, pointing to the next item in the list - the item containing x. This has a next property, which is the item containing a. The function then calls a third copy of itself with this item, and so on and so forth until it hits the final e, and calls a copy of itself with the next property of that item - that is to say, it calls itself with NULL as the input.



            This copy of the function then returns due to the if statement- crucially, it returns to the function that called it, in this case the copy of itself the level above. This copy then carries on where it left off, executing printf("%d ", head->data); - in this case, it prints an e. Then it falls out of the body of the function and so returns to the function that called it. This copy of the function will have a head->data value of l, and this will print as above. As such, it then runs through back up the chain until it gets to the original function call, prints the first e, and then returns to the function that called it.



            Hope this makes sense, I know it's not the best or most elegant explanation of recursion but there's a lot of material out there if this is confusing explaining exactly how recursion works and how useful it can be!







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 1 '17 at 0:51









            ACascarinoACascarino

            922814




            922814























                0














                The thing that makes it go in reverse is to have the printf() call after the recursive call to itself.



                You can try interchanging the two calls as in



                void printNormal(struct node* head)
                {
                // Base case
                if (head == NULL)
                return;

                // Before all, we print this node info.
                printf("%d ", head->data);

                // print the rest of the list after this node
                printReverse(head->next);

                }


                And you'll get the forward printing of the list.



                The mission of the so commented Base case is to avoid infinite recursion. The end of the list is special, we can do the check on entering the printReverse() function, so we can deal with the special case of an empty list, or we have to do it at each call (then we should put a check before calling the function inside it, and in the code that calls the recursive function (better to put it at the beginning).






                share|improve this answer




























                  0














                  The thing that makes it go in reverse is to have the printf() call after the recursive call to itself.



                  You can try interchanging the two calls as in



                  void printNormal(struct node* head)
                  {
                  // Base case
                  if (head == NULL)
                  return;

                  // Before all, we print this node info.
                  printf("%d ", head->data);

                  // print the rest of the list after this node
                  printReverse(head->next);

                  }


                  And you'll get the forward printing of the list.



                  The mission of the so commented Base case is to avoid infinite recursion. The end of the list is special, we can do the check on entering the printReverse() function, so we can deal with the special case of an empty list, or we have to do it at each call (then we should put a check before calling the function inside it, and in the code that calls the recursive function (better to put it at the beginning).






                  share|improve this answer


























                    0












                    0








                    0







                    The thing that makes it go in reverse is to have the printf() call after the recursive call to itself.



                    You can try interchanging the two calls as in



                    void printNormal(struct node* head)
                    {
                    // Base case
                    if (head == NULL)
                    return;

                    // Before all, we print this node info.
                    printf("%d ", head->data);

                    // print the rest of the list after this node
                    printReverse(head->next);

                    }


                    And you'll get the forward printing of the list.



                    The mission of the so commented Base case is to avoid infinite recursion. The end of the list is special, we can do the check on entering the printReverse() function, so we can deal with the special case of an empty list, or we have to do it at each call (then we should put a check before calling the function inside it, and in the code that calls the recursive function (better to put it at the beginning).






                    share|improve this answer













                    The thing that makes it go in reverse is to have the printf() call after the recursive call to itself.



                    You can try interchanging the two calls as in



                    void printNormal(struct node* head)
                    {
                    // Base case
                    if (head == NULL)
                    return;

                    // Before all, we print this node info.
                    printf("%d ", head->data);

                    // print the rest of the list after this node
                    printReverse(head->next);

                    }


                    And you'll get the forward printing of the list.



                    The mission of the so commented Base case is to avoid infinite recursion. The end of the list is special, we can do the check on entering the printReverse() function, so we can deal with the special case of an empty list, or we have to do it at each call (then we should put a check before calling the function inside it, and in the code that calls the recursive function (better to put it at the beginning).







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 2 '17 at 10:45









                    Luis ColoradoLuis Colorado

                    4,4001718




                    4,4001718























                        0














                        As others have already explained the recursive version. I suggest you to have a look at this iterative version of printing linked list in reverse order. This is more easy to understand and implement as compared to recursive version, however it increases time complexity.



                            // To ease testing of code here linked list is created randomly of given size.
                        #include<stdio.h>
                        #include<cstdlib>
                        #include<time.h>
                        #define size 10 //Size of list
                        struct node
                        {
                        int info;
                        struct node * next;
                        };
                        typedef struct node* Node;
                        Node start;
                        int main()
                        {
                        int i;
                        srand(time(NULL));
                        for(i=0;i<size;i++)
                        {
                        Node ptr;
                        ptr=(Node)malloc(sizeof(node));
                        ptr->info=rand()%100; //random list is created of given size.
                        ptr->next=NULL;
                        if(start==NULL)
                        start=ptr;
                        else
                        {
                        ptr->next=start;
                        start=ptr;
                        }
                        }
                        printf(" Traversal of Linked List in forward direction -n");
                        Node temp=start;
                        while(temp!=NULL)
                        {
                        printf(" %d ",temp->info);
                        temp=temp->next;
                        }
                        printf("n Traversal of Linked List in backward direction -n");
                        Node ptr=NULL;
                        while(ptr!=start)
                        {
                        temp=start;
                        while(temp->next!=ptr)
                        temp=temp->next;
                        printf(" %d ",temp->info);
                        ptr=temp;
                        }
                        return 0;
                        }


                        For more details visit-
                        https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git






                        share|improve this answer




























                          0














                          As others have already explained the recursive version. I suggest you to have a look at this iterative version of printing linked list in reverse order. This is more easy to understand and implement as compared to recursive version, however it increases time complexity.



                              // To ease testing of code here linked list is created randomly of given size.
                          #include<stdio.h>
                          #include<cstdlib>
                          #include<time.h>
                          #define size 10 //Size of list
                          struct node
                          {
                          int info;
                          struct node * next;
                          };
                          typedef struct node* Node;
                          Node start;
                          int main()
                          {
                          int i;
                          srand(time(NULL));
                          for(i=0;i<size;i++)
                          {
                          Node ptr;
                          ptr=(Node)malloc(sizeof(node));
                          ptr->info=rand()%100; //random list is created of given size.
                          ptr->next=NULL;
                          if(start==NULL)
                          start=ptr;
                          else
                          {
                          ptr->next=start;
                          start=ptr;
                          }
                          }
                          printf(" Traversal of Linked List in forward direction -n");
                          Node temp=start;
                          while(temp!=NULL)
                          {
                          printf(" %d ",temp->info);
                          temp=temp->next;
                          }
                          printf("n Traversal of Linked List in backward direction -n");
                          Node ptr=NULL;
                          while(ptr!=start)
                          {
                          temp=start;
                          while(temp->next!=ptr)
                          temp=temp->next;
                          printf(" %d ",temp->info);
                          ptr=temp;
                          }
                          return 0;
                          }


                          For more details visit-
                          https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git






                          share|improve this answer


























                            0












                            0








                            0







                            As others have already explained the recursive version. I suggest you to have a look at this iterative version of printing linked list in reverse order. This is more easy to understand and implement as compared to recursive version, however it increases time complexity.



                                // To ease testing of code here linked list is created randomly of given size.
                            #include<stdio.h>
                            #include<cstdlib>
                            #include<time.h>
                            #define size 10 //Size of list
                            struct node
                            {
                            int info;
                            struct node * next;
                            };
                            typedef struct node* Node;
                            Node start;
                            int main()
                            {
                            int i;
                            srand(time(NULL));
                            for(i=0;i<size;i++)
                            {
                            Node ptr;
                            ptr=(Node)malloc(sizeof(node));
                            ptr->info=rand()%100; //random list is created of given size.
                            ptr->next=NULL;
                            if(start==NULL)
                            start=ptr;
                            else
                            {
                            ptr->next=start;
                            start=ptr;
                            }
                            }
                            printf(" Traversal of Linked List in forward direction -n");
                            Node temp=start;
                            while(temp!=NULL)
                            {
                            printf(" %d ",temp->info);
                            temp=temp->next;
                            }
                            printf("n Traversal of Linked List in backward direction -n");
                            Node ptr=NULL;
                            while(ptr!=start)
                            {
                            temp=start;
                            while(temp->next!=ptr)
                            temp=temp->next;
                            printf(" %d ",temp->info);
                            ptr=temp;
                            }
                            return 0;
                            }


                            For more details visit-
                            https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git






                            share|improve this answer













                            As others have already explained the recursive version. I suggest you to have a look at this iterative version of printing linked list in reverse order. This is more easy to understand and implement as compared to recursive version, however it increases time complexity.



                                // To ease testing of code here linked list is created randomly of given size.
                            #include<stdio.h>
                            #include<cstdlib>
                            #include<time.h>
                            #define size 10 //Size of list
                            struct node
                            {
                            int info;
                            struct node * next;
                            };
                            typedef struct node* Node;
                            Node start;
                            int main()
                            {
                            int i;
                            srand(time(NULL));
                            for(i=0;i<size;i++)
                            {
                            Node ptr;
                            ptr=(Node)malloc(sizeof(node));
                            ptr->info=rand()%100; //random list is created of given size.
                            ptr->next=NULL;
                            if(start==NULL)
                            start=ptr;
                            else
                            {
                            ptr->next=start;
                            start=ptr;
                            }
                            }
                            printf(" Traversal of Linked List in forward direction -n");
                            Node temp=start;
                            while(temp!=NULL)
                            {
                            printf(" %d ",temp->info);
                            temp=temp->next;
                            }
                            printf("n Traversal of Linked List in backward direction -n");
                            Node ptr=NULL;
                            while(ptr!=start)
                            {
                            temp=start;
                            while(temp->next!=ptr)
                            temp=temp->next;
                            printf(" %d ",temp->info);
                            ptr=temp;
                            }
                            return 0;
                            }


                            For more details visit-
                            https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 2 at 17:53









                            Sahdev KansalSahdev Kansal

                            11




                            11























                                -1














                                Jim Rodgers hits the nail on the head. However, you could make life very easy for yourself by having a doubly linked list.



                                So for example your entry (node) has both a previous and next member pointing to the previous entry and next entry respectively. Then you don't need more "obfuscated" code than necessary.






                                share|improve this answer
























                                • This answer has nothing to do with the sense of the question. The SO wants to understand why it works that way and how to do in the opposite direction, and you are blaming about some programming customs that are far of being of interest here (or even useful).

                                  – Luis Colorado
                                  Jan 2 '17 at 10:48











                                • LOL! So in the context of singly linked list (and its reversal), some friendly advice as to the use of the natural alternative, the doubly linked list, is of no use. BTW, when you need to reverse search or indeed swap entries in a linked list, the doubly linked data structure is the advised option in cases where memory is not severely limited. BTW, I like the way you think I was talking about a "custom" rather than a data structure.

                                  – cdcdcd
                                  Jan 2 '17 at 13:25













                                • reLOL! the exercise was about recursive function calls, and not on double linked lists. I know a double linked list allows you to traverse it either direction, but the question was Is the return statement what makes it go step by step back? Or something else? and not what is the best linked list implementation to traverse it backwards?

                                  – Luis Colorado
                                  Jan 3 '17 at 12:17













                                • Luis see first line of question: "I was searching on how can I print a reverse of linked list and I found this piece of code". The issue of reverse ordering was the focus of his original problem. The issue of recursion was a fallout of this original problem and led to the question. I was simply pointing him to a simpler solution if this approach is causing him some consternation. Personally, I find (from experience) more general answers give helpful leads. If it is not welcome I'll take it down.

                                  – cdcdcd
                                  Jan 3 '17 at 12:44











                                • You are right in that complete general answers are better than simple or nongeneral ones. But recursion is a general technique that must be studied also, even not being many times the best approach to a problem. The first example in studying recursion is normally the factorial one, which no one solves by a recursive function in reality, and questions arise on that, but nobody answers it saying that recursion is something to be avoided. Not before having a good knowledge.

                                  – Luis Colorado
                                  Jan 4 '17 at 8:24
















                                -1














                                Jim Rodgers hits the nail on the head. However, you could make life very easy for yourself by having a doubly linked list.



                                So for example your entry (node) has both a previous and next member pointing to the previous entry and next entry respectively. Then you don't need more "obfuscated" code than necessary.






                                share|improve this answer
























                                • This answer has nothing to do with the sense of the question. The SO wants to understand why it works that way and how to do in the opposite direction, and you are blaming about some programming customs that are far of being of interest here (or even useful).

                                  – Luis Colorado
                                  Jan 2 '17 at 10:48











                                • LOL! So in the context of singly linked list (and its reversal), some friendly advice as to the use of the natural alternative, the doubly linked list, is of no use. BTW, when you need to reverse search or indeed swap entries in a linked list, the doubly linked data structure is the advised option in cases where memory is not severely limited. BTW, I like the way you think I was talking about a "custom" rather than a data structure.

                                  – cdcdcd
                                  Jan 2 '17 at 13:25













                                • reLOL! the exercise was about recursive function calls, and not on double linked lists. I know a double linked list allows you to traverse it either direction, but the question was Is the return statement what makes it go step by step back? Or something else? and not what is the best linked list implementation to traverse it backwards?

                                  – Luis Colorado
                                  Jan 3 '17 at 12:17













                                • Luis see first line of question: "I was searching on how can I print a reverse of linked list and I found this piece of code". The issue of reverse ordering was the focus of his original problem. The issue of recursion was a fallout of this original problem and led to the question. I was simply pointing him to a simpler solution if this approach is causing him some consternation. Personally, I find (from experience) more general answers give helpful leads. If it is not welcome I'll take it down.

                                  – cdcdcd
                                  Jan 3 '17 at 12:44











                                • You are right in that complete general answers are better than simple or nongeneral ones. But recursion is a general technique that must be studied also, even not being many times the best approach to a problem. The first example in studying recursion is normally the factorial one, which no one solves by a recursive function in reality, and questions arise on that, but nobody answers it saying that recursion is something to be avoided. Not before having a good knowledge.

                                  – Luis Colorado
                                  Jan 4 '17 at 8:24














                                -1












                                -1








                                -1







                                Jim Rodgers hits the nail on the head. However, you could make life very easy for yourself by having a doubly linked list.



                                So for example your entry (node) has both a previous and next member pointing to the previous entry and next entry respectively. Then you don't need more "obfuscated" code than necessary.






                                share|improve this answer













                                Jim Rodgers hits the nail on the head. However, you could make life very easy for yourself by having a doubly linked list.



                                So for example your entry (node) has both a previous and next member pointing to the previous entry and next entry respectively. Then you don't need more "obfuscated" code than necessary.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jan 1 '17 at 0:57









                                cdcdcdcdcdcd

                                448512




                                448512













                                • This answer has nothing to do with the sense of the question. The SO wants to understand why it works that way and how to do in the opposite direction, and you are blaming about some programming customs that are far of being of interest here (or even useful).

                                  – Luis Colorado
                                  Jan 2 '17 at 10:48











                                • LOL! So in the context of singly linked list (and its reversal), some friendly advice as to the use of the natural alternative, the doubly linked list, is of no use. BTW, when you need to reverse search or indeed swap entries in a linked list, the doubly linked data structure is the advised option in cases where memory is not severely limited. BTW, I like the way you think I was talking about a "custom" rather than a data structure.

                                  – cdcdcd
                                  Jan 2 '17 at 13:25













                                • reLOL! the exercise was about recursive function calls, and not on double linked lists. I know a double linked list allows you to traverse it either direction, but the question was Is the return statement what makes it go step by step back? Or something else? and not what is the best linked list implementation to traverse it backwards?

                                  – Luis Colorado
                                  Jan 3 '17 at 12:17













                                • Luis see first line of question: "I was searching on how can I print a reverse of linked list and I found this piece of code". The issue of reverse ordering was the focus of his original problem. The issue of recursion was a fallout of this original problem and led to the question. I was simply pointing him to a simpler solution if this approach is causing him some consternation. Personally, I find (from experience) more general answers give helpful leads. If it is not welcome I'll take it down.

                                  – cdcdcd
                                  Jan 3 '17 at 12:44











                                • You are right in that complete general answers are better than simple or nongeneral ones. But recursion is a general technique that must be studied also, even not being many times the best approach to a problem. The first example in studying recursion is normally the factorial one, which no one solves by a recursive function in reality, and questions arise on that, but nobody answers it saying that recursion is something to be avoided. Not before having a good knowledge.

                                  – Luis Colorado
                                  Jan 4 '17 at 8:24



















                                • This answer has nothing to do with the sense of the question. The SO wants to understand why it works that way and how to do in the opposite direction, and you are blaming about some programming customs that are far of being of interest here (or even useful).

                                  – Luis Colorado
                                  Jan 2 '17 at 10:48











                                • LOL! So in the context of singly linked list (and its reversal), some friendly advice as to the use of the natural alternative, the doubly linked list, is of no use. BTW, when you need to reverse search or indeed swap entries in a linked list, the doubly linked data structure is the advised option in cases where memory is not severely limited. BTW, I like the way you think I was talking about a "custom" rather than a data structure.

                                  – cdcdcd
                                  Jan 2 '17 at 13:25













                                • reLOL! the exercise was about recursive function calls, and not on double linked lists. I know a double linked list allows you to traverse it either direction, but the question was Is the return statement what makes it go step by step back? Or something else? and not what is the best linked list implementation to traverse it backwards?

                                  – Luis Colorado
                                  Jan 3 '17 at 12:17













                                • Luis see first line of question: "I was searching on how can I print a reverse of linked list and I found this piece of code". The issue of reverse ordering was the focus of his original problem. The issue of recursion was a fallout of this original problem and led to the question. I was simply pointing him to a simpler solution if this approach is causing him some consternation. Personally, I find (from experience) more general answers give helpful leads. If it is not welcome I'll take it down.

                                  – cdcdcd
                                  Jan 3 '17 at 12:44











                                • You are right in that complete general answers are better than simple or nongeneral ones. But recursion is a general technique that must be studied also, even not being many times the best approach to a problem. The first example in studying recursion is normally the factorial one, which no one solves by a recursive function in reality, and questions arise on that, but nobody answers it saying that recursion is something to be avoided. Not before having a good knowledge.

                                  – Luis Colorado
                                  Jan 4 '17 at 8:24

















                                This answer has nothing to do with the sense of the question. The SO wants to understand why it works that way and how to do in the opposite direction, and you are blaming about some programming customs that are far of being of interest here (or even useful).

                                – Luis Colorado
                                Jan 2 '17 at 10:48





                                This answer has nothing to do with the sense of the question. The SO wants to understand why it works that way and how to do in the opposite direction, and you are blaming about some programming customs that are far of being of interest here (or even useful).

                                – Luis Colorado
                                Jan 2 '17 at 10:48













                                LOL! So in the context of singly linked list (and its reversal), some friendly advice as to the use of the natural alternative, the doubly linked list, is of no use. BTW, when you need to reverse search or indeed swap entries in a linked list, the doubly linked data structure is the advised option in cases where memory is not severely limited. BTW, I like the way you think I was talking about a "custom" rather than a data structure.

                                – cdcdcd
                                Jan 2 '17 at 13:25







                                LOL! So in the context of singly linked list (and its reversal), some friendly advice as to the use of the natural alternative, the doubly linked list, is of no use. BTW, when you need to reverse search or indeed swap entries in a linked list, the doubly linked data structure is the advised option in cases where memory is not severely limited. BTW, I like the way you think I was talking about a "custom" rather than a data structure.

                                – cdcdcd
                                Jan 2 '17 at 13:25















                                reLOL! the exercise was about recursive function calls, and not on double linked lists. I know a double linked list allows you to traverse it either direction, but the question was Is the return statement what makes it go step by step back? Or something else? and not what is the best linked list implementation to traverse it backwards?

                                – Luis Colorado
                                Jan 3 '17 at 12:17







                                reLOL! the exercise was about recursive function calls, and not on double linked lists. I know a double linked list allows you to traverse it either direction, but the question was Is the return statement what makes it go step by step back? Or something else? and not what is the best linked list implementation to traverse it backwards?

                                – Luis Colorado
                                Jan 3 '17 at 12:17















                                Luis see first line of question: "I was searching on how can I print a reverse of linked list and I found this piece of code". The issue of reverse ordering was the focus of his original problem. The issue of recursion was a fallout of this original problem and led to the question. I was simply pointing him to a simpler solution if this approach is causing him some consternation. Personally, I find (from experience) more general answers give helpful leads. If it is not welcome I'll take it down.

                                – cdcdcd
                                Jan 3 '17 at 12:44





                                Luis see first line of question: "I was searching on how can I print a reverse of linked list and I found this piece of code". The issue of reverse ordering was the focus of his original problem. The issue of recursion was a fallout of this original problem and led to the question. I was simply pointing him to a simpler solution if this approach is causing him some consternation. Personally, I find (from experience) more general answers give helpful leads. If it is not welcome I'll take it down.

                                – cdcdcd
                                Jan 3 '17 at 12:44













                                You are right in that complete general answers are better than simple or nongeneral ones. But recursion is a general technique that must be studied also, even not being many times the best approach to a problem. The first example in studying recursion is normally the factorial one, which no one solves by a recursive function in reality, and questions arise on that, but nobody answers it saying that recursion is something to be avoided. Not before having a good knowledge.

                                – Luis Colorado
                                Jan 4 '17 at 8:24





                                You are right in that complete general answers are better than simple or nongeneral ones. But recursion is a general technique that must be studied also, even not being many times the best approach to a problem. The first example in studying recursion is normally the factorial one, which no one solves by a recursive function in reality, and questions arise on that, but nobody answers it saying that recursion is something to be avoided. Not before having a good knowledge.

                                – Luis Colorado
                                Jan 4 '17 at 8:24


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41412592%2ffunction-to-print-linked-list-in-reverse-order%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Mossoró

                                Error while reading .h5 file using the rhdf5 package in R

                                Pushsharp Apns notification error: 'InvalidToken'