且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

反转链表

更新时间:2023-11-10 09:28:28

假设我有一个链表: / p>

Suppose I have a linked list:

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

您的代码将其转换为:

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

请注意,第一个元素仍然指向2。

Notice that the first element still points back to 2.

如果添加行 parent-> next = NULL 前两个,你会得到:

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

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

其实是正确的结构。

完整的代码是:(您只需要打印每个递归调用的当前值)



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;
       }

  }