数据结构(严蔚敏)算法2.7
-----------------------------------------------------------------------------------
Problem:顺序表的合并:两个升序线性表a和b,合并成一个线性表c,时间复杂度为O(La.lenth+Lb.lenth)。
-----------------------------------------------------------------------------------
代码区
#include <iostream>
#include <malloc.h>
using namespace std;
struct List
{
int * sta;
int lenth;
int loclen;
};
void InitList(List* Ls,int lenth);
void InputList(List* Ls);
void SortList(List* Ls);
void ShowList(const List* Ls);
void MergeList(List* a,List* b);
int main()
{
List la,lb;
int alen,blen;
cout<<"请输入初始化表a,表b的长度"<<endl;
cin>>alen>>blen;
cout<<"请初始化表a的数值"<<endl;
InitList(&la,alen);
InputList(&la);
SortList(&la);
cout<<"请初始化表b的数值"<<endl;
InitList(&lb,blen);
InputList(&lb);
SortList(&lb);
cout<<"当前表a的数值为:"<<endl;
ShowList(&la);
cout<<"当前表b的数值为:"<<endl;
ShowList(&lb);
cout<<"当前表c的数值为:"<<endl;
MergeList(&la,&lb);
return 0;
}
void InitList(List* Ls,int lenth)
{
Ls->sta=(int *)malloc(sizeof(int)*lenth);
if(!Ls->sta)
{
cout<<"内存分配失败!!!"<<endl;
exit;
}
Ls->loclen=0;
Ls->lenth=lenth;
}
void InputList(List* Ls)
{
cout<<"请输入表中元素"<<endl;
for(int i=0;i<Ls->lenth;i++)
cin>>Ls->sta[i];
Ls->loclen=Ls->lenth;
}
void SortList(List* Ls)
{
int i,j;
for(i=0;i<Ls->lenth-1;i++)
for(j=i+1;j<Ls->lenth;j++)
{
if(Ls->sta[i]>Ls->sta[j])
{
int temp=Ls->sta[i];
Ls->sta[i]=Ls->sta[j];
Ls->sta[j]=temp;
}
}
}
void ShowList(const List* Ls)
{
int*p=Ls->sta,*pe=&Ls->sta[Ls->loclen-1],i=0;
for(p;p<=pe;p++,i++)
cout<<*p<<" ";
cout<<endl;
}
void MergeList(List* a,List* b)
{
int* p1=a->sta,*p2=b->sta;
int Lenth_C=a->lenth+b->lenth;
List c,*LC=&c;
InitList(LC,Lenth_C);
int*p1end=&a->sta[a->lenth-1];
int*p2end=&b->sta[b->lenth-1];
while(p1<=p1end&&p2<=p2end)
{
if(*p1<*p2)
LC->sta[LC->loclen]=*p1++;
else
LC->sta[LC->loclen]=*p2++;
LC->loclen++;
}
while(p1<=p1end)
{
LC->sta[LC->loclen]=*p1++;
LC->loclen++;
}
while(p2<=p2end)
{
LC->sta[LC->loclen]=*p2++;
LC->loclen++;
}
int*p=LC->sta,*pe=&LC->sta[LC->loclen-1],i=0;
for(p;p<=pe;p++,i++)
cout<<*p<<" ";
cout<<endl;
}
结果:
