【问题标题】:Recursive method for reversing singly linked list?用于反转单链表的递归方法?
【发布时间】: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


【解决方案1】:

那么,当您尝试更改时发生了什么?当然当然你可以写它……但语义可能会改变。

first->next 分配给rest 并不强制它们始终相同。您前面的语句将一个指向rest指针 传递到recursiveReverse。简而言之,您期望 rest 会改变。

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

这是否足以说明问题?如果不是,请添加一些打印语句来说明您的程序在每种情况下的作用。

【讨论】:

  • C 没有通过引用。指向rest指针 是按值传递的,这不是一回事。但是,它确实提供了相同的可能性,即 rest 的值在调用者中被修改。
  • 关于:“是什么让你思考 [...]” 可能是因为它在许多其他领域都以这种方式工作:例如,函数式编程和数学。具有副作用的功能是/不/直观的。请以不那么居高临下的方式重写您的答案。
猜你喜欢
  • 1970-01-01
  • 2018-11-16
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多