您的位置:首页 > 科技 > 能源 > 8月28c++

8月28c++

2024/10/7 18:09:25 来源:https://blog.csdn.net/A111222129/article/details/141648844  浏览:    关键词:8月28c++

 c++手动封装顺序表

#include <iostream>using namespace std;
using datatype =int;//类型重命名struct SeqList
{
private:datatype *data;//顺序表数组int size=0;//数组大小int len=0;//顺序表实际长度
public:void init(int s);//初始化函数bool empty();//判空函数bool full();//判满函数bool add(datatype e);//添加数据函数int length();//求顺序表实际长度bool insert_pos(int pos,datatype e);//任意位置插入函数bool delete_pos(int pos);//任意位置删除函数datatype &at(int index);//访问任意一个元素函数void expand();//二倍扩容函数
};
//初始化函数
void SeqList::init(int s)
{size=s;data=new datatype(size);
}
//判空
bool SeqList::empty()
{return len==0;//实际长度是否为0
}bool SeqList::full()
{return len==size;//实际长度是否为最大大小
}
//添加
bool SeqList::add(datatype e)
{   //判满if(full()){return 0;}data[len]=e;//添加len++;//长度加1return 1;
}
//实际长度
int SeqList::length()
{return len;//返回实际长度
}
//任意位置插入
bool SeqList::insert_pos(int pos, datatype e)
{//判满和插入位置if(full()||pos<1||pos>len+1){return 0;}int i;//后一个等于前一个for(i=len;i>pos-1;i--){data[i]=data[i-1];}//按位置插入data[i]=e;len++;//实际长度加一return 1;
}
//任意位置删除
bool SeqList::delete_pos(int pos)
{//判空和删除位置if(empty()||pos<1||pos>len){return 0;}//前一个等于后一个for(int i=pos;i<len;i++){data[i-2]=data[i-1];}len--;//实际长度减一data[len]=0;//最后一个数据清零return 1;
}datatype& SeqList::at(int index)
{return data[index];//返回任意位置数据
}void SeqList::expand()
{size=size*2;//二倍最大长度datatype *temp=new datatype[size];//堆区创建数组空间//搬运原数组for(int i=0;i<len;i++){temp[i]=data[i];}delete[]data;//销毁原堆区空间data=temp;//指针重新指向该堆区空间
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com