#include <iostream>
using namespace std;
#define INITSIZE 5 //初始大小
#define EXTSIZE 3 //每次扩展的大小
typedef int ElemType;
struct SeqList
{
ElemType* data;
unsigned int maxsize; //顺序表的当前容量
size_t length;
};
void Clearlist(SeqList& LL)
{
LL.length = 0;
memset(LL.data, 0, sizeof(ElemType) * LL.maxsize);
}
void initlist(SeqList& LL)
{
LL.maxsize = INITSIZE;
LL.data = new ElemType[LL.maxsize];
Clearlist(LL);
}
void destroylist(SeqList& LL)
{
delete[] LL.data;
LL.data = NULL;
LL.length = 0;
LL.maxsize = 0;
}
bool exlist(SeqList& LL)
{
ElemType* newdata = new (std::nothrow)ElemType[LL.maxsize + EXTSIZE];
if (newdata == NULL) {return false;}
memset(newdata, 0, (sizeof(ElemType)) * (LL.maxsize + EXTSIZE));
memcpy(newdata, LL.data, LL.length*sizeof(ElemType));
delete[] LL.data;
LL.data = newdata;
LL.maxsize = LL.maxsize + EXTSIZE;
return true;
}
bool Insertlist(SeqList& LL, size_t pos, ElemType& ee)
{
if (LL.length == LL.maxsize)
{
if (exlist(LL) == false)
{
cout << "扩展失败" << endl;
return false;
}
}
if ((pos < 1) || (pos > LL.length + 1)) { cout << "插入位置错误" << endl; return false; }
if (pos < LL.length + 1)
memcpy(LL.data + pos, LL.data + pos - 1, (LL.length - pos + 1) * sizeof(ElemType));
memcpy(&LL.data[pos - 1], &ee, sizeof(ElemType));
LL.length++;
return true;
}
bool deletelist(SeqList& LL, size_t pos)
{
if ((pos < 1) || (pos > LL.length + 1))
{
cout << "删除位置错误" << endl;
return false;
}
memmove(&LL.data[pos - 1], &LL.data[pos], (LL.length - pos) * sizeof(ElemType));
LL.length--;
return true;
}
void printlist(const SeqList& LL)
{
if (LL.length == 0)
{
cout << "空表!" << endl;
return;
}
for (size_t i = 0; i < LL.length; i++)
{
cout << LL.data[i] << "\t";
}
cout << endl;
return;
}
size_t getlength(const SeqList& LL)
{
return LL.length;
}
size_t getmaxsize(const SeqList& LL)
{
return LL.maxsize;
}
int main()
{
SeqList LL;
initlist(LL);
ElemType ee;
ee = 1;
Insertlist(LL, 1, ee);
printlist(LL);
cout <<"长度: "<< getlength(LL) << endl;
cout<<"最大空间:"<<getmaxsize(LL) << endl;
ee = 2;
Insertlist(LL, 1, ee);
printlist(LL);
cout << "长度: " << getlength(LL) << endl;
cout << "最大空间:" << getmaxsize(LL) << endl;
Insertlist(LL, 1, ee);
Insertlist(LL, 1, ee);
Insertlist(LL, 1, ee);
Insertlist(LL, 1, ee);
printlist(LL);
cout << "长度: " << getlength(LL) << endl;
cout << "最大空间:" << getmaxsize(LL) << endl;
deletelist(LL, 3);
printlist(LL);
cout << "长度: " << getlength(LL) << endl;
cout << "最大空间:" << getmaxsize(LL) << endl;
destroylist(LL);
}