【发布时间】:2017-08-16 13:21:02
【问题描述】:
我是 C 的新手,我正在尝试创建一个函数来反转链表,仅将 List 本身作为参数传递。如果不将节点作为参数传递,这可能吗?
到目前为止,这是我的代码,我知道它不能正常工作,因为我不知道如何对列表的其余部分进行递归调用。
void reverse(LL_t *L) {
if (L->head->next == NULL) {
return;
}
node_t *rest = L->head->next;
reverse(rest);
node_t *q = rest->next;
q->next = rest;
rest->next = NULL;
}
这也是我的类型定义。
typedef struct {
node_t *head;
node_t *tail;
} LL_t;
typedef struct _node {
int data;
struct _node *next;
} node_t;
【问题讨论】:
-
编写另一个从节点进行反转的函数(未在 API 中公开)。
-
reverse(rest);类型不匹配。reverse需要LL_t*但rest的类型是node_t*。 -
@BLUEPIXY 我不确定如何将“休息”变成 LL_t*,以便它包含除当前头部之外的所有元素
-
不需要将其设为递归调用,但对于递归调用,
LL_t只是一个持有者,因此使用node_t作为参数是有意义的。 -
与其将
reverse本身作为递归函数,不如将补充函数(例如void reverse_aux(LL_t*, node_t*)等)作为递归函数呢?
标签: c recursion linked-list