手动封装一个顺序表(SeqList),分文件编译实现
有私有成员:顺序表数组的起始地址 ptr、 顺序表的总长度:size、顺序表的实际长度:len
成员函数:初始化 init(int n)
判空:empty
判满:full
尾插:push_back
插入:insert(int index)
任意位置删除:erase(int index)
尾删: pop_back
求长度:size()
获取任意位置元素:& at(int inex)
将顺序表进行排序:sort(bool flag) //flag 为真,表示升序,否则是降序
#include <iostream>
#include <string.h>
using namespace std;
using lili=int;
class SeqList
{
private:lili *ptr;lili size;lili len=0;
public:void init (lili n){this->ptr =new lili[n];this->size=n;this->len=0;}bool empty(){return this->len==0;}bool full(){return this->size==this->len;}void push_back(lili e){if(this->full()){return ;}this->ptr[len++]=e;}void out(){if(this->empty()){return ;}cout <<"当前顺序表的元素分别是:";for(int i=0;i<this->len;i++){cout <<this->ptr[i]<<" ";}cout <<endl;}void insert(lili n,lili m){if(this->full()){return;}for(int i=this->len++;i>=m;i--){this->ptr[i]=this->ptr[i-1];}this->ptr[m-1]=n;}void pop_back(){if(this->empty()){return ;}this->ptr[len-1]=this->ptr[len];this->len--;}void dele(lili n){if(this->empty()){return ;}for(int i=n-1;i<len;i++){this->ptr[i]=this->ptr[i+1];}this->len--;}lili size_len(){return this->len;}lili &at(lili n){return this->ptr[n-1];}void sort(bool flag){lili x;if(flag!=0){for(int i=0;i<this->len;i++){for(int j=0;j<this->len-1-i;j++){if(this->ptr[j]>this->ptr[j+1]){x=this->ptr[j];this->ptr[j]=this->ptr[j+1];this->ptr[j+1]=x;}}}}else{for(int i=0;i<this->len;i++){for(int j=0;j<this->len-1-i;j++){if(this->ptr[j]<this->ptr[j+1]){x=this->ptr[j];this->ptr[j]=this->ptr[j+1];this->ptr[j+1]=x;}}}}}
};int main()
{SeqList s1;s1.init(5);s1.push_back(5);s1.push_back(9);s1.push_back(3);s1.push_back(7);s1.out();s1.insert(6,3);s1.out();s1.pop_back();s1.out();s1.dele(3);s1.out();cout <<s1.size_len()<<endl;cout <<s1.at(2)<<endl;s1.sort(1);s1.out();return 0;
}