有鉴于这题不少人卡在莫名其妙的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;
}