这道题的算法思想是建立一个空表,通过建立顺序链表,让指针依次指向原来两个链表中较小的元素。
代码如下:
#include <stdio.h>
#include <malloc.h>
struct node{/*单链表的定义*/
int data;
struct node* next;
};
struct node* Createlist(int n){/*顺序建立单链表*/
struct node* head,*tail,*p;
int i,d;
head=(struct node*)malloc(sizeof(struct node));
tail=head;
for(i=1;i<=n;i++){
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&d);
p->data=d;
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
};
struct node* Mergelist(struct node* head1,struct node* head2,struct node* head3){/*将两个一定顺序排列的单链表归并成一个有顺序的单链表*/
struct node* tail;
tail=head3;
while(head1&&head2){/*将指针指向较小的元素构成新的单链表*/
if (head1->data<head2->data){
tail->next=head1;
tail=head1;
head1=head1->next;
}
else{
tail->next=head2;
tail=head2;
head2=head2->next;
}
}
if(head1){
tail->next=head1;
}
if(head2){
tail->next=head2;
}
return head3;
};
int main(){
struct node*head1,*head2,*head3,*p,*q1,*q2;
p=(struct node*)malloc(sizeof(struct node));
head3=(struct node*)malloc(sizeof(struct node));/*为head3申请内存空间*/
int i,j,m,n;
scanf("%d %d",&m,&n);
head1=Createlist(m);
head2=Createlist(n);
q1=head1->next;
q2=head2->next;
head3->next=NULL;/*建立空表*/
head3=Mergelist(q1,q2,head3);
for(p=head3->next;p!=NULL;p=p->next){
if (p==head3->next)
printf("%d",p->data);
else
printf(" %d",p->data);
}
return 0;
}