Problem Description
已知顺序表A与B是两个有序的顺序表,其中存放的数据元素皆为普通整型,将A与B表归并为C表,要求C表包含了A、B表里所有元素,并且C表仍然保持有序。
Input
输入分为三行:
第一行输入m、n(1<=m,n<=10000)的值,即为表A、B的元素个数;
第二行输入m个有序的整数,即为表A的每一个元素;
第三行输入n个有序的整数,即为表B的每一个元素;Output
输出为一行,即将表A、B合并为表C后,依次输出表C所存放的元素。
Sample Input
5 3
1 3 5 6 9
2 4 10Sample Output
1 2 3 4 5 6 9 10
题解:和链表操作的思想一样。依次比较就可以了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int maxn = 10000;
struct node
{
int *elem;
int len;
};
void Creatlist(int len, struct node &list)
{
list.elem = (int *)malloc(maxn * sizeof(int));
list.len = len;
for(int i = 0; i < len; i ++)
{
scanf("%d", &list.elem[i]);
}
}
void Merge(struct node &list1, struct node &list2, struct node &list)
{
list.elem = (int *)malloc(2 * maxn * sizeof(int));
int i = 0, j = 0, k = 0;
for(; i < list1.len && j < list2.len;)
{
if(list1.elem[i] > list2.elem[j])
{
list.elem[k ++] = list2.elem[j];
j ++;
}
else
{
list.elem[k ++] = list1.elem[i];
i ++;
}
}
if(i == list1.len)
{
for(j = j; j < list2.len; j ++)
list.elem[k ++] = list2.elem[j];
}
else
{
for(i = i; i < list1.len; i ++)
list.elem[k ++] = list2.elem[i];
}
list.len = k;
}
void print(struct node &list)
{
for(int i = 0; i < list.len - 1; i ++)
printf("%d ", list.elem[i]);
printf("%d",list.elem[list.len-1]);
printf("\n");
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
struct node list1,list2,list;
Creatlist(n,list1);
Creatlist(m,list2);
Merge(list1,list2,list);
print(list);
return 0;
}
标签:顺序,int,list,elem,len,list2,++,SDUT,3329 From: https://blog.51cto.com/u_15965659/6056606