题目描述

已知线性表 LA 和 LB 中的数据元素按值非递减有序排列,现要求将 LA 和 LB 归并为一个新的线性表 LC, 且 LC 中的数据元素仍然按值非递减有序排列。例如,设LA=(3,5,8,11) ,LB=(2,6,8,9,11,15,20) 则

LC=(2,3,6,6,8,8,9,11,11,15,20)

算法描述如下:

从上述问题要求可知,LC中的数据元素或是LA中的数据元素,或是LB中的数据元素,则只要先设LC为空表,然后将LA或LB中的元素逐个插入到LC中即可。为使LC中元素按值非递减有序排列,可设两个指针 i 和 j 分别指向LA和LB中某个元素,若设 i 当前所指的元素为 a,j 所指的元素为 b,则当前应插入到 LC 中的元素 c 为 c = a < b ? a : b显然,指针 i 和 j 的初值均为1(实际写代码时往往是从 0 开始的),在所指元素插入 LC 之后,在 LA 或者 LB 中顺序后移。

输入格式

有多组测试数据,每组测试数据占两行。第一行是集合A,第一个整数m0<=m<=100)代表集合A起始有m个元素,后面有m个非递减排序的整数,代表A中的元素。第二行是集合B,第一个整数n(0<=n<=100)代表集合B起始有n个元素,后面有n个非递减排序的整数,代表B中的元素。每行中整数之间用一个空格隔开。

输出

每组测试数据只要求输出一行,这一行含有 m+n 个来自集合 A 和集合中的元素。结果依旧是非递减的。每个整数间用一个空格隔开。

样例输入

4 3 5 8 11

7 2 6 8 9 11 15 20

样例输出

2 3 5 6 8 8 9 11 11 15 20

 总结:

      本题书中提供的算法是基于顺序表的。在使用顺序表时需要两倍于数据元素数目。如果使用链表则只需要存储一倍的元素。然而使用链表同样需要存储一倍的指针。所以对于这类问题数据结构的选取,如果数据域占用的空间很大则可以使用链表存储来节省空间,而对于数据域占用不大的情况,则使用顺序表也可以。

代码如下:

#include
#include
typedef struct node{    int data;    node *next;}LinkList;void InitList(LinkList *&L){    L = (LinkList *)malloc(sizeof(LinkList));    L->next = NULL;}void CreateList(LinkList *&L,int n,int a[]){    LinkList *r = L, *s;    int i;    for(i = 0; i < n; i++)    {        s = (LinkList *)malloc(sizeof(LinkList));        s->data = a[i];        r->next = s;        r = s;    }    r->next = NULL;}void Union(LinkList *&L1,LinkList *L2,LinkList *L3){    LinkList *p = L2->next, *q = L3->next, *r = L1,*s;    while(p && q)    {        if(p->data <= q->data)        {            s = (LinkList *)malloc(sizeof(LinkList));            s->data = p->data;            r->next = s;            r = s;            p = p->next;        }        else        {            s = (LinkList *)malloc(sizeof(LinkList));            s->data = q->data;            r->next = s;            r = s;            q = q->next;        }    }    if(p)        r->next = p;    else        r->next = q;}void DispList(LinkList *L){    if(L->next == NULL)    {        printf("\n");        return ;    }    LinkList *p = L->next;    while(p->next != NULL)    {        printf("%d ",p->data);        p = p->next;    }    printf("%d\n",p->data);}int main(){    LinkList *L1,*L2,*L3;    int m, n, a[101], b[101], i;    while(scanf("%d",&n) != EOF)    {        InitList(L1);        InitList(L2);        InitList(L3);        for(i = 0; i < n; i++)            scanf("%d",&a[i]);        CreateList(L2,n,a);        scanf("%d",&m);        for(i = 0; i < m; i++)            scanf("%d",&b[i]);        CreateList(L3,m,b);        Union(L1,L2,L3);        DispList(L1);    }    return 0;}