看板 b99902HW 關於我們 聯絡資訊
有鑑於這題不少人卡在莫名其妙的bug(?) 就放個簡單的測試在上面囉~ 然後小小的建議,做完malloc後最好對拿到的記憶體初始化一下, 比較不容易出錯這樣, 像是講義上的 assert(); 就是為了避免沒初始化的情形發生~ #include<stdio.h> #include<stdlib.h> struct listnode{ int data; struct listnode *next; }; /* put your code here. */ void print(struct listnode *now){ while(now!=NULL){ printf("%d ", now->data); now=now->next; } puts(""); return; } int main(){ int i; struct listnode *list1, *list2, *ptr, *now; list1=(struct listnode*)malloc(sizeof(struct listnode)); list2=(struct listnode*)malloc(sizeof(struct listnode)); for(i=0, now=list1; i<10; i+=2){ ptr=(struct listnode*)malloc(sizeof(struct listnode)); ptr->next=NULL; ptr->data=i; now->next=ptr; now=now->next; } list1=list1->next; printf("now print the content of list1\n"); print(list1); for(i=1, now=list2; i<10; i+=2){ ptr=(struct listnode*)malloc(sizeof(struct listnode)); ptr->next=NULL; ptr->data=i; now->next=ptr; now=now->next; } for( ; i<=15; i++){ ptr=(struct listnode*)malloc(sizeof(struct listnode)); ptr->next=NULL; ptr->data=i; now->next=ptr; now=now->next; } list2=list2->next; printf("now print the content of list2\n"); print(list2); now=merge_linked_lists(list1, list2); printf("now print the content of your list\n"); print(now); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.91.122
m80126colin:推真強者 11/30 20:59
wctaiwan:感謝,今天弄超久的 11/30 23:26
rod24574575:然後11.2傳上去時好像要自己附一下標頭檔 11/30 23:31
rod24574575:我一開始沒附結果他跟我說NULL不能用... 11/30 23:31
fei6409:應該是11.3? 我是傳這題才有用標頭檔... 12/01 00:01
m80126colin:我也是有用到標頭檔.......如果NULL寫成0就不用?? 12/01 00:20
rod24574575:喔 我有點忘記是哪個了 反正都附就不會錯 (? 12/01 00:33
garychou:雖然我寫好了 還是推一下囉 第三題的確要傳標頭檔 12/01 22:58
sandy30716:第三題有測試用的嗎? 12/01 23:17