2016-09-15 111 views
1

我在反向单链表的递归方法?

http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/

看到这个递归程序(C语言)扭转单向链表。

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; 

我可以写 “休息 - >下一=第一;” 代替 “一线>下一步 - >下一=第一;”?

或者是否有写“first-> next-> next = first;”的意义?

+0

http://stackoverflow.com/questions/37725393/reverse-linked-list-recursively – BLUEPIXY

回答

0

那么,当你尝试这种变化时发生了什么? 当然你可以写它......但语义可能会改变。

first->next指定为rest并不强制它们始终保持一致。您的紧前面的声明将指针传递给rest转换为recursiveReverse。总之,你预计rest改变。

rest现在应该指向其余列表的头部。这不再是first->next;现在应该是反向列表的结束,其中rest是该列表的头部。

这是否足以说明问题?如果没有,请填写一些印刷说明来说明您的程序在每种情况下的作用。

+1

C没有通过引用传递。指向“rest”的*指针是通过值传递的,这不是一回事。然而,它确实提供了在调用者中修改'rest'的值的可能性。 –

+0

关于:“什么让你觉得[......]”可能的事实是,它在许多其他领域以这种方式工作:例如,函数式编程和数学。具有副作用的功能是/不直观的。请用不那么居高临下的方式重写你的答案。 –