题目:使用C++手动封装一个顺序表,包含成员数组一个,成员变量N个
#include <iostream>using namespace std;//类型重命名
using datatype = int; //typedef int datatype;
#define MAX 30struct SeqList
{private:// datatype data[MAX] = {0}; //顺序表的数组datatype *data; //顺序表的数组int size = 0; //数组的大小int len = 0; //顺序表实际长度public://初始化函数void init(int s){size = s; //当前数组的最大容量data = new datatype(size); //在堆区申请一个顺序表容器}//要实现的函数//判空函数bool empty();//判满函数bool full();//添加数据函数bool add(datatype e);//求当前顺序表的实际长度int length();//展示数据void show();//任意位置插入函数bool insert_pos(int pos, datatype e);//任意位置删除函数bool delete_pos(int pos);//访问容器中任意一个元素 atdatatype at(int index);
};//判空函数
bool SeqList::empty()
{return len==0;
}
//盘满函数
bool SeqList::full()
{return len==size;
}
//添加数据函数
bool SeqList::add(datatype e)
{if(full()){cout<<"顺序表已满"<<endl;return false;}data[len++]=e;return true;
}
//求顺序表得实际长度
int SeqList::length()
{if(empty()){return false;}return len;
}
//展示函数
void SeqList::show()
{for(int i=0;i<len;i++){cout<<data[i]<<" ";}cout<<""<<endl;
}
//返回任意位置函数
bool SeqList::delete_pos(int pos)
{if(empty()){return false;}for(int i=pos;i<len-1;i++){data[i]=data[i+1];}len--;cout<<"删除成功"<<endl;return true;
}
//任意位置插入函数
bool SeqList::insert_pos(int pos, datatype e)
{if(full()){cout<<"顺序表已满"<<endl;return false;}for(int i=len-1;i>=pos;i--){data[i+1]=data[i];}data[pos]=e;len++;cout<<"插入成功"<<endl;return true;
}//访问任意元素
datatype SeqList::at(int index)
{return data[index];
}int main()
{SeqList list;list.init(MAX);//添加数据list.add(5);list.add(2);list.add(0);//任意位置插入list.insert_pos(1,1);list.insert_pos(2,3);list.insert_pos(3,1);list.insert_pos(4,4);//展示数据list.show();//删除list.delete_pos(0);list.delete_pos(5);list.delete_pos(5);//展示数据list.show();//访问数据cout<<"访问数据:"<<list.at(3)<<endl;//返回数据表长度cout<<"数据表长度:"<<list.length()<<endl;return 0;
}