#include
#include
typedef struct node
{
int a;
struct node *next;
}*List,list;
List create(int start,int end)
{
List head=(list*)malloc(sizeof(list));
List p=head;
for(int i=start;i<=end;i++){
List t=(list*)malloc(sizeof(list));
t->a=i;
t->next=NULL;
p->next=t;
p=p->next;
}
return head;
}
void print(List head){
List p=head;
while(p){
printf("%3d",p->a);
p=p->next;
}
puts("");
}
List merge(List h1,List h2){
List p=(list*)malloc(sizeof(list));
List r=p;
h1=h1->next;
h2=h2->next;
while(h1 || h2){
if(h1==NULL){
p->next=h2;
p=p->next;
h2=h2->next;
continue;
}
if(h2==NULL){
p->next=h1;
p=p->next;
h1=h1->next;
continue;
}
if(h1->a>h2->a){
p->next=h2;
p=p->next;
h2=h2->next;
}
else {
p->next=h1;
p=p->next;
h1=h1->next;
}
}
return r;
}
int main(){
List h1=create(5,10);
List h2=create(10,15);
List h=merge(h1,h2);
print(h);
return 0;
}
if(h1->a>h2->a){
p->next=h2;
p=p->next;
h2=h2->next;
}
else if(h1->a < h2->a){
p->next=h1;
p=p->next;
h1=h1->next;
}
else{
p->next=h2;
p=p->next;
h2=h2->next; //反正兩個鏈表頭元素相等,隨便加入一個
h1 = h1->next;//將另外一個無視掉就可以了
}
另外在print(h)之前最好加上h = h->next;因為按照你的寫法,鏈表h的頭元素其實是多余的