Day1:顺序表应用5:有序顺序表归并

匿名 (未验证) 提交于 2019-12-02 22:56:40

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

Sample Input

 5 3 1 3 5 6 9 2 4 10

Sample Output

 1 2 3 4 5 6 9 10
 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define max 10010 typedef int element; typedef struct {     element *elem;     int length; }list; void creat(list &L) {     L.elem = (element *)malloc(sizeof(element) * max);     L.length = 0; } void input(list &L, int n) {     int i;     L.length = n;     for(i=0; i<n; i++)     {         scanf("%d", &L.elem[i]);     } } void move_behind(list &L, int h) {     int i, t;     t = L.elem[L.length-1];     for(i=L.length-1; i>=h; i--)     {         L.elem[i] = L.elem[i-1];     }     L.elem[L.length] = t;     L.length++; } void combine(list &A, list &B) {     int i, j = 0;     for(i=0; i<A.length; i++)     {         if(A.elem[i] > B.elem[j])         {             move_behind(A, i);             A.elem[i] = B.elem[j];             j++;         }     }     if(j < B.length)     {         for(i=j; i<B.length; i++)         {             A.elem[A.length] = B.elem[i];             A.length++;         }     } } void input(list &L) {     int i;     for(i=0; i<L.length-1; i++)         printf("%d ", L.elem[i]);     printf("%d\n", L.elem[L.length-1]); } int main() {     list A, B;     int n, m;     scanf("%d %d", &n, &m);     creat(A);     creat(B);     input(A, n);     input(B, m);     combine(A, B);     input(A);     return 0; } 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!