顺序表之有序顺序表归并

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BHliuhan/article/details/82558373

顺序表应用5:有序顺序表归并
Time Limit: 100 ms Memory Limit: 880 KiB

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 10
Sample Output
1 2 3 4 5 6 9 10
Hint
Source

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LISTSIZE 10000
#define LISTINCREASEMENT  100
typedef struct
{
    int *elem;
    int length;
    int listsize;
}Sqlist;
void InitList(Sqlist&L)
{
    L.elem=(int*)malloc(LISTSIZE*(sizeof(int)));
    L.length=0;
    L.listsize=LISTSIZE;
}
void ListInsert(Sqlist&L,int i,int e)
{
    if(L.length>=L.listsize)
    {
        int *newbase=(int *)realloc(L.elem,(L.listsize+LISTINCREASEMENT)*sizeof(int));
        L.elem=newbase;
        L.listsize=L.listsize+LISTINCREASEMENT;
    }
    L.elem[i]=e;
    L.length++;
}
void mergelist(Sqlist&L1,Sqlist&L2,Sqlist&L3)
{
    int i=0,j=0,k=0;
    while(i<L1.length&&j<L2.length)
    {
        if(L1.elem[i]<L2.elem[j])
        {
            ListInsert(L3,k++,L1.elem[i++]);
        }
        else
        {
            ListInsert(L3,k++,L2.elem[j++]);
        }
    }
    while(i<L1.length)
    {
        ListInsert(L3,k++,L1.elem[i++]);
    }
    while(j<L2.length)
    {
        ListInsert(L3,k++,L2.elem[j++]);
    }
    for(int h=0;h<L3.length;h++)
    {
        if(h==0)printf("%d",L3.elem[h]);
        else printf(" %d",L3.elem[h]);
    }
    printf("\n");
}
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    Sqlist L3,L1,L2;
    InitList(L1);
    InitList(L2);
    InitList(L3);
    for(int i=0;i<n;i++)
    {
        int e;
        scanf("%d",&e);
        ListInsert(L1,i,e);
    }
    for(int i=0;i<m;i++)
    {
        int e;
        scanf("%d",&e);
        ListInsert(L2,i,e);
    }
    mergelist(L1,L2,L3);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/BHliuhan/article/details/82558373