顺序表还是简单的,就是写的有点累,不多讲了,直接看代码吧,要是有问题请自己想一想。
另外,书本上有逻辑位置这一说——我偷懒,所有的都是从0开始数,0,1,2,3,4……
1.创建、删除与清空
list(int n){
head=(Data *)malloc(n*sizeof(Data));
if(head==nullptr)
{
cout<<"初始化分配内存出错啦!"<
2.各种访问
void ListTraverse()
{
for(int i=0;ilength)
{
cout<<"访问不合法"<
3.修改、插入与删除元素
bool SetElem(int pos,Data e)
{
if(pos<0||pos>length)
{
cout<<"fail in SetElem"<length)
{
cout<<"invalid"<=size)
{
Data *newbase=(Data *)realloc(head,2*size*sizeof(Data));//默认双倍扩容
if(newbase==nullptr)
{
cout<<"failed to reverse"<=pos;j--)
{
head[j+1]=head[j];//向后拷贝,节约时间
}
head[pos]=e;
++length;
return true;
}
Data DeleteElem(int pos)//删除指定位置上的元素并返回
{
if(pos<0||pos>length)
{
cout<<"invalid"<
4.完整代码
#include
#include
using namespace std;
template
class list{
private:
Data *head;
int length;
int size;
public:
//1.create destroy and clear
list(int n){
head=(Data *)malloc(n*sizeof(Data));
if(head==nullptr)
{
cout<<"初始化分配内存出错啦!"<length)
{
cout<<"访问不合法"<length)
{
cout<<"fail in SetElem"<length)
{
cout<<"invalid"<=size)
{
Data *newbase=(Data *)realloc(head,2*size*sizeof(Data));//默认双倍扩容
if(newbase==nullptr)
{
cout<<"failed to reverse"<=pos;j--)
{
head[j+1]=head[j];//向后拷贝,节约时间
}
head[pos]=e;
++length;
return true;
}
Data DeleteElem(int pos)//删除指定位置上的元素并返回
{
if(pos<0||pos>length)
{
cout<<"invalid"<
好活,已抄