1

I'm a newbie of programming. I have wrote a function to scan inputs to linked list. But it does not work. Can anyone help me find what the problem is?

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;
}

and ListNode is defined as

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

Thank you!

man chan
  • 11
  • 1

1 Answers1

0

I had to take your code and try to reproduce the errors you are getting. Your code looks fine except that it gives compile-times errors as it fails to infer the type for ListNode. Typical errors are I getting that I think you are:

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

There are two solution alternatives:

One, modify the struct definition as below. With this approach, your code works like a charm.

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

Two, retain the definition of your struct but precede every struct variable declaration with keyword struct. E.g; instead of ListNode *list,*list2=NULL; do struct ListNode *list,*list2=NULL;

I tried to run your code, the sample input, and produced output is below. I hope this is how you expect your function to behave.

1 2 3 4 5 6 7 8 9 // <- input
9 8 7 6 5 4 3 2 // <- output
hmatar
  • 2,437
  • 2
  • 17
  • 27