reversing linked list

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

    You need to set the new tail (i.e the old head)'s next pointer to NULL

    EDIT: Here's a recursive version

    node *reverse_list_recursive(node *list)
      {
          node *parent = list;
          node *child = list->next;
          node *new_head;
    
    
        if (child == NULL)
              return parent ;  /* new head */
    
        new_head = reverse_list_recursive(child)
        child->next = parent; /* Old parent is the new child of the old child when reversed */
        parent->next = NULL; /* might be tail, will be overwritten after we return if we're not at the top level */
        return new_head;
    }
    

提交回复
热议问题