【发布时间】:2017-01-23 20:16:01
【问题描述】:
我在
中见过这个递归程序(用 C 语言)http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/
用于反转单链表。
void recursiveReverse(struct node** head_ref){
struct node* first;
struct node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->next;
/* List has only one node */
if (rest == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;}
在程序的这一步中,
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
我可以写“rest->next = first;”而不是“first->next->next = first;”吗?
或者写“first->next->next = first;”有什么意义?
【问题讨论】:
标签: c recursion singly-linked-list generic-programming