2017-03-15 62 views
1

我是一個編程新手。我寫了一個函數來掃描輸入到鏈表。但它不起作用。任何人都可以幫我找到問題所在嗎?掃描輸入到鏈接列表

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

謝謝!

+0

歡迎來到Stack Overflow! [請參閱此討論,爲什麼不在'C'中投射'malloc()'和family的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+4

「不起作用」不是一個有用的問題陳述。請閱讀https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – StoryTeller

+1

1)''%d%1 [^ \ n] s「'是錯誤的。 – BLUEPIXY

回答

0

我不得不採取你的代碼,並嘗試重現你所得到的錯誤。 你的代碼看起來很好,除非編譯時錯誤,因爲它無法推斷出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