【问题标题】:i'm trying to print linked list reverse via recursion but it doesn't work [closed]我正在尝试通过递归打印反向链接列表,但它不起作用[关闭]
【发布时间】:2017-02-18 11:28:43
【问题描述】:

我尝试通过递归以相反的顺序打印链表。
这是代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct list {
    int value;
    struct list* next;
} list_s;

static int g_size=sizeof(list_s);

void printRe(list_s *node) {
    if (node = NULL)
        return;
    printRe(node->next); // this is where error happens
    printf("%d", node->value);
}

int main() {
    list_s *head;
    head = (list_s*)malloc(g_size);

    int n;
    scanf("%d",&n);

    int i = 0;
    int x;
    scanf("%d", &x);

    head->value = x;
    head->next = NULL;

    list_s *current;
    current = head;
    for (i; i < n - 1; ++i) {
        current->next = (list_s*)malloc(g_size);
        current = current->next;
        scanf("%d", &x);
        current->value = x;
        current->next = NULL;
    };
    printRe(head);
    return 0;  
}   

如您所见,当我尝试打印 node->next 时发生错误。为什么会发生错误?我是否以错误的方式将列表传递给函数?

谢谢!

【问题讨论】:

  • node=NULL 在那个 if 测试中应该是 node==NULL
  • gcc -Wall 大喊warning: suggest parentheses around assignment used as truth value [-Wparentheses] if(node=NULL)

标签: c recursion printing linked-list


【解决方案1】:

如果 printRe() 函数中的条件应该是这样的

if(node==NULL) 而不是 if(node=NULL)

希望对你有所帮助。 谢谢

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 1970-01-01
    • 2014-07-30
    • 2021-11-30
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2013-06-02
    相关资源
    最近更新 更多