我需要用下面的代碼幫助有關鏈接列表:鍛鍊; Tibial約C列出
#include <stdlib.h>
#include <stdio.h>
struct nodo {
int d;
struct nodo *next;
};
struct nodo *full();
int main()
{
struct nodo *l;
/* l=(struct nodo *)malloc(sizeof(struct nodo)); */
l = full();
while(l!=NULL) {
printf("-->%d\n", l->d);
l =l->next;
}
system("PAUSE");
}
struct nodo *full()
{
int i;
struct nodo *head, *nes;
head = (struct nodo *)malloc(sizeof(struct nodo));
head->next = NULL;
for(i = 1; i < 5; i++) {
nes = (struct nodo *)malloc(sizeof(struct nodo));
printf("Insert the %d element:\n", i);
scanf("%d", &nes->d);
nes->next = head;
head = nes;
}
return head;
}
如果我嘗試例如輸入1, 2, 3, 4
,我得到下面的輸出:
-->4
-->3
-->2
-->1
-->9708864
爲什麼我得到最後一個號碼?我的代碼有什麼問題?
這功課嗎?另外:1.不需要輸入'malloc'的結果,2.在調用'full()'之前不需要'malloc',3.你沒有調用'free()'... – 2012-07-13 12:04:23
@EitanT當然是;如果不是的話,OP就不敢投入malloc()的返回值。 – 2012-07-13 12:06:24
@EitanT我總是投下malloc的結果,因爲是的,這是一個家庭作業,如果我不投,我的編譯器返回這個錯誤:無效轉換從'void *'到'nodo *'我應該在哪裏打電話免費? – gyosko 2012-07-13 12:10:14