2017-04-22 36 views
0

我有點卡在如何使用戶定義的函數打印輸出。我還必須創建一個用戶定義的函數,將每個節點中的數據相加並打印出總數,但它不能正確累加,並且格式稍微偏離。用戶定義函數和鏈接列表C

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

char printout(); 
int sum(); 
typedef struct node 
{ 
    int number; 
    struct node*next; 
} node; 

char printout() 
{ 

}; 
int sum() 
{ 
    int s,sum_all=0, node_sum=0; 
    for(s=0;s=100;s++) 
    { 
     sum_all=node_sum+s; 
     return printf("The sum of all nodes is %d.\n",sum_all); 
    }; 

}; 
int main() 
{ 
    srand (time(NULL)); 
    int i, total=0; 
    struct node*head=malloc(sizeof(struct node)); 
    head->number = rand()%100; 
    printf("Node #%d contains %d.\n", 0, head->number); 

    struct node*here=head; 

    for (i=1; i<100; i++) 
    { 
     here->next=malloc(sizeof(struct node)); 
     here->number=rand()%100; 
     printf("Node #%d contains %d.\n", i, here->number); 
    }; 
    total=sum(here->number); 
    printf("%2.2d", total); 
    return 0; 
} 
+1

我不明白插入是如何工作的:(你在每次循環時覆蓋'here-> next'而不將它存儲在任何地方,即泄漏它。關於鏈表的事情是元素必須實際上是鏈接:) – ThingyWotsit

+0

第一次迭代時,函數'sum'中'for'循環的重點是什麼? –

+0

爲什麼返回類型的函數'printout'' char'? – BLUEPIXY

回答

1

有錯誤的一連串這裏,但我們只專注於最重要的肉:

你應該在名單的頭傳遞給函數sum(),即

sum(head); // This is how you call most linked list functions. 

其中你應該改變標頭爲

int sum(struct node *head) 
{ ... } 

這不是一個數組。你應該正確地遍歷鏈表。

我無法爲您顯示所有代碼,因爲這是您的教授希望您學習的內容。

但是,你應該使用這些

for(struct node*p = head; p!=NULL; p=p->next) 

,而不是這些

for(s=0; s<=100; s++) 

你也忘了你的malloc - 充填 - 與蘭特環挺身而出

這裏= here-> next; //這確實在鏈表我++並在陣列

sum_all += p->number; // p->number is analogous to array[i] 

sum_all = node_sum +s; // what are s and node_sum anyway? 

而且相反,如果你堅持要和一些回報, 它應該返回,以及, 總和;

return sum_all; 

而且不要打印功能

printf("The sum of all nodes is %d.\n",sum_all); // please don't 

裏面因爲你已經在外面打印。

total = sum(head); 
printf("%2.2d", total); 

請儘量先考慮一下你的代碼將要完成的事情,而不是盲目地放置代碼。 它會幫助你很多。祝你好運!

+1

我什至沒有注意到這一點。感謝您的提示。我在編程方面真的很新穎,這也是我第一個學期,我很遺憾你必須教我。 – Viridian

+0

回覆我的回答,我很抱歉,如果我的話有點兒,混蛋。 我知道很多誰通過指針遭遇的人是CS1,和鏈表偏偏又喚醒惡夢:( 從我的經驗,他們學會了更快的通過使每個操作的比喻數組。 我希望你們從所有學習這些:) – Karl

+1

這是沒有問題的,我真的很感謝所有的幫助,我可以得到。 – Viridian