數據結構實驗之鏈表四:有序鏈表的歸併
Problem Description
Input
第二行依次輸入M個有序的整數;
第三行依次輸入N個有序的整數。
Output
Example Input
6 5 1 23 26 45 66 99 14 21 28 50 100
Example Output
1 14 21 23 26 28 45 50 66 99 100
Hint
Author
參考代碼
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int n,m;
struct node *head1,*head2,*tail,*p,*q;
head1 = (struct node *)malloc(sizeof(struct node));
head2 = (struct node *)malloc(sizeof(struct node));
head1->next = head2->next =NULL;
scanf("%d%d",&n,&m);
tail = head1;
while(n--)
{
p = (struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next = tail->next;
tail->next = p;
tail = p;
}
tail = head2;
while(m--)
{
p = (struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next = tail->next;
tail->next = p;
tail = p;
}
p = head1->next;
q = head2->next;
tail = head1;
head1->next = head2->next = NULL;
while( p && q )
{
if( p->data > q->data )
{
tail->next = q;
tail = q;
q = q->next;
}
else
{
tail->next = p;
tail = p;
p = p->next;
}
}
if(p)
{
tail->next = p;
}
else
{
tail->next = q;
}
p = head1->next;
printf("%d",p->data);
p = p->next;
while(p)
{
printf(" %d",p->data);
p = p->next;
}
printf("\n");
return 0;
}