reversing linked list

后端 未结 9 1183
星月不相逢
星月不相逢 2020-12-10 16:52

I am trying to reverse a linked list using recursion and wrote the following code for it. The list is start of the list at the beginning.

 node *reverse_lis         


        
9条回答
  •  庸人自扰
    2020-12-10 17:07

    Suppose I have a linked list:

     ----------      ----------      ----------      ---------- 
    |  1  |    |--->|  2  |    |--->|  3  |    |--->|  4  |    |--->NULL
     ----------      ----------      ----------      ---------- 
    

    Your code converts it to:

       ----------------------          ----------------------
       |                    |          |                    |
       v                    |          v                    |
     ----------      ----------      ----------      ----------
    |  1  |    |--->|  2  |    |    |  3  |    |    |  4  |    | 
     ----------      ----------      ----------      ---------- 
                       ^                    |
                       |                    |
                       ----------------------
    

    Notice that the first element still points back to 2.

    If you add the line parent->next = NULL after the first two, you will get:

               ----------------------          ----------------------
               |                    |          |                    |
               v                    |          v                    |
             ----------      ----------      ----------      ----------
    NULL<---|  1  |    |    |  2  |    |    |  3  |    |    |  4  |    | 
             ----------      ----------      ----------      ---------- 
                               ^                    |
                               |                    |
                               ----------------------
    

    which is in fact the correct structure.

    The complete code is: (You only need to print the current value for each recursive call)

    node *reverse_list_recursive(node *list)
      {
          node *parent = list;
          node *current = list->next;
    
          if(current == NULL)
           return parent;
    
          else
           {
               current = reverse_list_recursive(current);
               parent->next = NULL;
               current->next = parent;
               printf("\n %d \n",current->value);
               return parent;
           }
    
      }
    

提交回复
热议问题