顺序表的简单实现。包括表的初始化,插入,删除,归并。内存分配使用C语言的malloc和realloc来实现。
假设在每个合法位置进行插入和删除操作的概率相等,则这两种操作每次的平均移动次数为n/2,时间复杂度为O(n)。
代码如下:
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define LISTINCREMENT 10
//表结构
typedef struct sqList{
int* elem; //数据区
int len; //当前长度
int listsize; //最大长度
};
//插入
bool insertList(sqList& L,int pos,int e)
{
//1~len+1为合法插入位置
if(pos<1||pos>L.len+1)
return false;
//扩容
if(L.len>=L.listsize)
{
int* newbase=(int*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int));
if(!newbase)
exit(-1);
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
int* pp=&L.elem[pos-1];//插入位置
int* q=&L.elem[L.len];
//依次后移
for(;q>=pp;q--)
{
*(q)=*(q-1);
}
*pp=e;
++L.len;
return true;
}
//删除
bool deleteList(sqList& L,int pos,int& e)
{
//1~len为合法删除位置
if(pos<1||pos>L.len)
return false;
int* p=&L.elem[pos-1]; //删除位置
e=*p; //返回被删元素
int* end=L.elem+L.len-1;
//依次迁移
for(++p;p<=end;++p)
{
*(p-1)=*p;
}
--L.len;
return true;
}
//初始化,分配内存
bool initList(sqList& L)
{
L.elem=(int*)malloc(LISTINCREMENT*sizeof(int));
L.len=0;
L.listsize=LISTINCREMENT;
return true;
}
//输出表
void outputList(const sqList& L)
{
if(L.len<1)
return;
for(int i=0;i<L.len;i++)
cout<<L.elem[i]<<endl;
cout<<endl;
}
//表排序
bool sortList(sqList& L)
{
if(L.len==0)
return false;
sort(L.elem,L.elem+L.len);
}
//合并有序表
bool mergeList(const sqList& L,const sqList& L2,sqList& L3)
{
L3.listsize=L.len+L2.len;
int l=0;
int l2=0;
while(l<L.len&&l2<L2.len)
{
if(L.elem[l]<L2.elem[l2])
{
insertList(L3,L3.len+1,L.elem[l]);
++l;
}
else
{
insertList(L3,L3.len+1,L2.elem[l2]);
++l2;
}
}
while(l<L.len)
{
insertList(L3,L3.len+1,L.elem[l]);
++l;
}
while(l2<L2.len)
{
insertList(L3,L3.len+1,L2.elem[l2]);
++l2;
}
return true;
}
int main()
{
sqList L,L2,L3;
if(!initList(L))
exit(-1);
if(!initList(L2))
exit(-1);
if(!initList(L3))
exit(-1);
for(int i=0;i<L.listsize;i++)
{
insertList(L,L.len+1,rand()%50);
}
for(int i=0;i<L2.listsize;i++)
{
insertList(L2,L2.len+1,rand()%100);
}
cout<<"Initial:\n";
outputList(L);
insertList(L,10,1000);
cout<<"Insert:\n";
outputList(L);
int e;
deleteList(L,10,e);
cout<<"Delete:\n";
outputList(L);
sortList(L);
cout<<"L1:\n";
outputList(L);
sortList(L2);
cout<<"L2:\n";
outputList(L2);
cout<<"Merge:\n";
mergeList(L,L2,L3);
outputList(L3);
return 0;
} 运行结果:
5166

被折叠的 条评论
为什么被折叠?



