順序表之有序順序表歸併
阿新 • • 發佈:2019-02-19
順序表應用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;
}