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所存放的元素。
Example Input
5 3 1 3 5 6 9 2 4 10
Example Output
1 2 3 4 5 6 9 10#include<stdio.h> #include<string.h> #include<stdlib.h> #define INITLISTSIZE 1000000 #define INCREMENT 10 #define OVERFLOW -2 #define ERROR -1 #define OK 1 typedef int Elemtype; typedef int Statu; int n, m; typedef struct node { Elemtype *elem; int length; int listsize; } Sqlist; Statu Initlist(Sqlist &L); Statu Insertlist(Sqlist &L, int i, int e); Statu Dellist(Sqlist &L, int i); int Search(Sqlist L, int e, int j); Statu Mergerlist(Sqlist La, Sqlist Lb, Sqlist &Lc); Statu Prelist(Sqlist L); Statu Destroylist(Sqlist &L); int main() { int i, j; Sqlist La, Lb, Lc; Initlist(La); Initlist(Lb); Initlist(Lc); scanf("%d %d", &n, &m); for(i = 0; i < n; i++) { scanf("%d", &j); Insertlist(La, i + 1, j); } for(i = 0; i < m; i++) { scanf("%d", &j); Insertlist(Lb, i + 1, j); } Mergerlist(La, Lb, Lc); Prelist(Lc); } Statu Initlist(Sqlist &L) { L.elem = (Elemtype *)malloc(INITLISTSIZE * sizeof(Elemtype)); if(!L.elem) return OVERFLOW; L.length = 0; L.listsize = INITLISTSIZE; return OK; } Statu Insertlist(Sqlist &L, int i, int e) { if(i < 1 || i > L.length + 1) return ERROR; if(L.length >= L.listsize) { L.elem = (Elemtype *)realloc(L.elem, (L.listsize + INCREMENT) * sizeof(Elemtype)); if(!L.elem) return OVERFLOW; L.listsize += INCREMENT; } for(int j = L.length; j >= i; j--) L.elem[j] = L.elem[j - 1]; L.elem[i - 1] = e; ++L.length; return OK; } Statu Dellist(Sqlist &L, int i) { if(i < 1 || i > L.length) return OVERFLOW; for(int j = i - 1; j < L.length; j++) L.elem[j] = L.elem[j + 1]; --L.length; return OK; } int Search(Sqlist L, int e, int j) { for(int i = 0; i < j; i++) { if(L.elem[i] == e) { return i; } } return -1; } Statu Mergerlist(Sqlist La, Sqlist Lb, Sqlist &Lc) { int a, b, c; a = b = 0; c = 1; while(a < n && b < m) { if(La.elem[a] < Lb.elem[b]) { Insertlist(Lc, c++, La.elem[a]); a++; } else { Insertlist(Lc, c++, Lb.elem[b]); b++; } } while(a < n) { Insertlist(Lc, c++, La.elem[a]); a++; } while(b < m) { Insertlist(Lc, c++, Lb.elem[b]); b++; } return OK; } Statu Prelist(Sqlist L) { for(int i = 0; i < L.length; i++) { printf("%d%c", L.elem[i], i == L.length - 1 ? '\n' : ' '); } return OK; } Statu Destroylist(Sqlist &L) { if(L.elem) { free(L.elem); L.length = 0; L.listsize = 0; } else return ERROR; return OK; }