SeqList.h
#ifndef SEQLIST_H
#define SEQLIST_H#include <iostream>
#include<memory.h>
#include<stdlib.h>
#include<string.h>using namespace std;//typedef int datatype; //类型重命名
using datatype = int;//封装一个顺序表
class SeqList
{
private:datatype *ptr; //指向堆区空间的起始地址int size; //总长度int len = 0; //当前顺序表实际长度public:void init(int n);//判空bool empty();//判满bool full();//尾插void push_back(datatype e);//任意位置插入void insert(int index);//任意位置删除void erase(int index);//定义展示函数void show();//求长度int get_size();//排序void sort(bool flag);//任意位置数据datatype& at(int index);//尾删void pop_back();};#endif // SEQLIST_H
SeqList.cpp
#include "SeqList.h"void SeqList::init(int n)
{//在堆区申请出一个长度为n的空间,将其实地址赋值给ptrthis->ptr = new datatype[n];//给len进行初始化this->len = 0;this->size = n;
}//判空
bool SeqList::empty()
{return this->len == 0;
}//判满
bool SeqList::full()
{return this->len == this->size;
}//尾插
void SeqList::push_back(datatype e)
{//判断是否满了if(this->full()){return ;}this->ptr[len++] = e;}//任意位置插入
void SeqList::insert(int index){//判满if(this->full()){cout<<"列表满"<<endl;return;}if(index>size){cout<<"超出容器大小"<<endl;return;}if(index<0){cout<<"位置不合法"<<endl;return;}int in;cout<<"请输入要插入的内容:"<<endl;cin>>in;for(int i=len;i>=index;i--){ptr[i] = ptr[i-1];cout<<ptr[i]<<endl;}ptr[index-1]=in;len++;
}//任意位置删除
void SeqList::erase(int index){if(index>size){cout<<"超出容器大小"<<endl;return;}if(index<0){cout<<"位置不合法"<<endl;return;}if(empty()){cout<<"表为空"<<endl;return;}for(int i=index-1;i<len-1;i++){ptr[i]=ptr[i+1];}len--;}//定义展示函数
void SeqList::show()
{//判空if(empty()){cout<<"表为空"<<endl;return;}cout<<"当前顺序表中的元素分别是:";for(int i=0; i<this->len; i++){cout<<this->ptr[i]<<" ";}cout<<endl;
}
//求总长
int SeqList::get_size(){return this->len;
}//获取任意位置的元素
datatype& SeqList::at(int index){return ptr[index-1];
}// 排序函数
void SeqList::sort(bool flag){for (int i=0; i<len-1;i++) {for (int j=0; j<len-1-i;j++) {if ((flag&&ptr[j]>ptr[j+1])||(!flag&&ptr[j]<ptr[j+1])) {// 交换元素datatype temp=ptr[j];ptr[j]=ptr[j+1];ptr[j+1]=temp;}}}
}//尾删
void SeqList::pop_back(){if(empty()){cout<<"列表为空"<<endl;return;}len--;
}
mian.cpp
#include "SeqList.h"using namespace std;int main()
{SeqList sl; //实例化一个顺序表对象sl.init(5); //申请空间sl.push_back(1111);sl.push_back(2222);sl.push_back(3333);//sl.insert(1);//sl.erase(2);//cout<<sl.at(2)<<endl;sl.sort(0);sl.show();return 0;
}