reversing linked list

后端 未结 9 1178
星月不相逢
星月不相逢 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:06

    I don't see the benefit of recursion here, iteration will work just as well. It's been forever since I've written C (and no easy way to test the following for syntax errors... or cringe core dumps, but you get the idea).

    node *reversed_list(node *list) {
        node *fwd=list;//Purely for readability
        node *last=null;
        node *next=null;
        node *rev=null;
        do {
            //Cache next
            next=fwd->next;
            //Set current
            rev=fwd;
            //Reset next to point back
            rev->next=last;
            //Update last
            last=fwd;
            //Forward ptr;
            fwd=next;
        } while (fwd!=null);
        return rev;
    }
    

    Pretty sure your *list is useless after you've called this since it's now pointing to last element of the list which has ->next=null, could just update that instead of returning the pointer.

    Update (for recursive solution)

    As others have said, your new tail is messed up (points back at the last element, but should point to null)... and you don't return the correct head, you return the second element. Consider the list a->b->null with your algorithm:

    p=a,
    c=b;
    c=
       p=b
       c=null
       return b; //b->null
    c=b
    c->next=a //b->a
    return a; //a->b, b->a, a returned
    //But what you wanted is a->null, b->a, and b returned
    

    The following updated code will fix:

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

    With list a->b->null:

    p=a,
    c=b;
    c=
       p=b
       c=null
       return b; //b->null
    c=b
    c->next=a //b->a
    p->next=null //a->null
    return b; // b->a->null
    

提交回复
热议问题