Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
分别输入两个有序的整数序列(分别包含M和N个数据),建立两个有序的单链表,将这两个有序单链表合并成为一个大的有序单链表,并依次输出合并后的单链表数据。
Input
第一行输入M与N的值;
第二行依次输入M个有序的整数;
第三行依次输入N个有序的整数。
Output
输出合并后的单链表所包含的M+N个有序的整数。
Sample Input
6 5
1 23 26 45 66 99
14 21 28 50 100
Sample Output
1 14 21 23 26 28 45 50 66 99 100
Hint
不得使用数组!
Source
先定义两个链表,在定义第三个链表,并对前两个链表从第一个开始比较,那一个小,边连接在第三个链表上;
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
int m,n,i,a1;
struct node *head1,*head2,*head3,*q,*p,*i1;
scanf("%d%d",&m,&n);
head1 = (struct node *)malloc(sizeof(struct node));
head1 -> next = NULL;
q = head1;
for(i=0; i<m; i++)
{
scanf("%d",&a1);
p = (struct node *)malloc(sizeof(struct node));
p -> next = NULL;
p -> a = a1;
q -> next = p;
q = p;
} //定义第一个链表;
head2 = (struct node *)malloc(sizeof(struct node));
head2 -> next = NULL;
q = head2;
for(i=0; i<n; i++)
{
scanf("%d",&a1);
p = (struct node *)malloc(sizeof(struct node));
p -> next = NULL;
p -> a = a1;
q -> next = p;
q = p;
} //定义第二个链表;
head3 = (struct node *)malloc(sizeof(struct node));
head3 -> next = NULL;
i1 = head1 -> next;
q = head2 -> next;
p = head3;
free(head1);
free(head2);
for(i=0;i<n+m;i++)
{
if(i1&&q)
{
if(i1 -> a < q -> a)
{
p -> next = i1;
p = i1;
i1 = i1 -> next;
}
else
{
p -> next= q;
p = q;
q = q -> next;
}
}
else
{
if(i1)
p -> next =i1;
if(q)
p -> next = q;
}
}
p = head3 -> next;
while(p)
{
if(p -> next)
printf("%d ",p -> a);
else printf("%d\n",p -> a);
p = p -> next;
}
return 0;
}