【问题标题】:scan inputs to linked list扫描输入到链表
【发布时间】:2017-03-15 06:27:33
【问题描述】:

我是编程新手。我写了一个函数来扫描链表的输入。但它不起作用。谁能帮我找出问题所在?

ListNode *BuildList() {
    char discard;
    ListNode *list,*list2=NULL;
    list = (ListNode*)malloc(sizeof(struct ListNode));
    if ((scanf("%d%1[^\n]s", &list->val, &discard)) == 2) {
        list->next = BuildList();
        printf("%d ", list->next->val);
    }
    else
    {
        list->next = NULL;
    }
    return list;
}

而ListNode被定义为

struct ListNode {
    int val;
    ListNode *next;
};

谢谢!

【问题讨论】:

标签: c linked-list


【解决方案1】:

我不得不使用您的代码并尝试重现您遇到的错误。 您的代码看起来不错,只是它给出了编译时错误,因为它无法推断 ListNode 的类型。 典型的错误是我认为你是:

test.c:11:5: error: unknown type name ‘ListNode’
     ListNode *list,*list2=NULL;

有两种解决方案可供选择:

一个,修改结构体定义如下。使用这种方法,您的代码就像一个魅力。

typedef struct ListNode {
  int val;
  struct ListNode *next;
} ListNode;

两个,保留结构的定义,但在每个结构变量声明之前使用关键字struct。例如;而不是ListNode *list,*list2=NULL;struct ListNode *list,*list2=NULL;

我尝试运行您的代码,示例输入和生成的输出如下。我希望这是你期望你的函数表现的方式。

1 2 3 4 5 6 7 8 9 // <- input
9 8 7 6 5 4 3 2 // <- output

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多