I am trying to print a linked list recursively. I created my own helper function for a recursive print, and I call it in my main print reverse function.
我试图递归打印链表。我为递归打印创建了自己的辅助函数,我在主打印反向函数中调用它。
What happens is, my pointer to the head of the list will successfully go to the last element of the list, but it will crash. I am not too sure on what exactly is happening here. I have checked for out of bounds with my !=NULL
. I am sort of lost on why it is not printing it backwards after the pointer has been established at the last integer. Here is my code.
会发生什么,我指向列表头部的指针将成功转到列表的最后一个元素,但它会崩溃。我不太清楚这里到底发生了什么。我用my!= NULL检查了越界。在指针在最后一个整数处建立后,为什么不向后打印它,我有点迷失。这是我的代码。
void lst_recursion(NODE *p){
while (p != NULL){
lst_recursion(p->next);
printf(FORMAT, p->val);
}
}
void lst_print_rev(LIST *l) {
NODE *p = l->front;
printf("[");
while (p!= NULL){
lst_recursion(p);
}
printf("]\n");
}
1 个解决方案
#1
2
First, you don't need a while
loop in any of this. The main entry point should look like this:
首先,你不需要在任何一个中使用while循环。主要入口点应如下所示:
void lst_print_rev(const LIST *l)
{
printf("[");
lst_recursion(l->front);
printf("]\n");
}
And the actual function, assuming your list is null-terminated, should look simply like this:
假设您的列表以空值终止,实际函数应该看起来像这样:
void lst_recursion(const NODE *p)
{
if (p == NULL)
return;
lst_recursion(p->next);
printf(FORMAT, p->val);
}
This will recurse to the tail, do nothing on that value (NULL), then unwind back up the activation stack, reporting each node on the way out. Remember, recursive algorithms need concrete exit strategies, and they're usually a simple if
condition to do nothing and just exit the call
这将递归到尾部,对该值不做任何操作(NULL),然后展开备份激活堆栈,在出路时报告每个节点。请记住,递归算法需要具体的退出策略,它们通常是一个简单的if条件,什么也不做,只是退出调用
Best of luck.
祝你好运。
#1
2
First, you don't need a while
loop in any of this. The main entry point should look like this:
首先,你不需要在任何一个中使用while循环。主要入口点应如下所示:
void lst_print_rev(const LIST *l)
{
printf("[");
lst_recursion(l->front);
printf("]\n");
}
And the actual function, assuming your list is null-terminated, should look simply like this:
假设您的列表以空值终止,实际函数应该看起来像这样:
void lst_recursion(const NODE *p)
{
if (p == NULL)
return;
lst_recursion(p->next);
printf(FORMAT, p->val);
}
This will recurse to the tail, do nothing on that value (NULL), then unwind back up the activation stack, reporting each node on the way out. Remember, recursive algorithms need concrete exit strategies, and they're usually a simple if
condition to do nothing and just exit the call
这将递归到尾部,对该值不做任何操作(NULL),然后展开备份激活堆栈,在出路时报告每个节点。请记住,递归算法需要具体的退出策略,它们通常是一个简单的if条件,什么也不做,只是退出调用
Best of luck.
祝你好运。