函数体
#include"SeqList.h"
void SeqList::init(int n)
{
this->ptr=new data[n];
this->len=0;
this->size=n;
}
bool SeqList::empty()
{
return this->len=0;
}
bool SeqList::full()
{
return this->size==this->len;
}
void SeqList::push_back(data e)
{
if(this->full())
{
return ;
}
this->ptr[len++]=e;
}
void SeqList::show()
{
for(int i=0;i<this->len;i++)
{
cout<<"元素"<<len<<this->ptr[i]<<" ";
}
cout<<endl;
}
void SeqList::insert(int index)
{
if(this->full())
{
return ;
}
if(index>this->len+1||index<=0||index>this->size)
{
cout<<"插入错误"<<endl;
return;
}
data e;
cout<<"输入要插入的元素";
cin>>e;
for(int i=len-1;i>=index-1;i--)
{
this->ptr[i+1]=this->ptr[i];
}
this->ptr[index-1]=e;
this->len++;
}
void SeqList::delete_s(int index)
{
if(index>this->len+1||index<=0||index>this->size)
{
cout<<"删除位置不合理"<<endl;
return;
}
for(int i=index;i<this->len;i++)
{
this->ptr[i-1]=this->ptr[i];
}
this->len--;
}
void SeqList::pop_back()
{
if(this->len==0)
{
cout<<"顺序表为空"<<endl;
return;
}
this->len--;
}
data SeqList::get_len()
{
return this->len;
}
data SeqList::get_index(int index)
{
if(index>this->len||index<0||index>=this->size)
{
cout<<"位置不合理";
return -1;
}
return this->ptr[index-1];
}
void SeqList::sort(bool flag)
{
if(flag){
for(int i=1;i<this->len;i++){
for(int j=0;j<this->len-i;j++){
if(this->ptr[j]>this->ptr[j+1]){
data t = this->ptr[j];
this->ptr[j] = this->ptr[j+1];
this->ptr[j+1] = t;
}
}
}
}
else{
for(int i=1;i<this->len;i++){
for(int j=0;j<this->len-i;j++){
if(this->ptr[j]<this->ptr[j+1]){
data t = this->ptr[j];
this->ptr[j] = this->ptr[j+1];
this->ptr[j+1] = t;
}
}
}
}
}
头文件
#ifndef SEQLIST_H
#define SEQLIST_H
#include<iostream>
#include<memory.h>
#include<stdlib.h>
#include<string.h>
using data=int;
using namespace std;
class SeqList
{
private:
data *ptr;
int size;
int len=0;
public:
void init(int n);
bool empty();
bool full();
void push_back(data e);
void show();
void insert(int index);
void delete_s(int index);
void pop_back();
data get_len();
data get_index(int index);
void sort(bool flag);
};
#endif // SEQLISH_H
主函数
#include"SeqList.h"
using namespace std;
int main()
{
SeqList s1;
int n;
cout << "输入顺序表的大小";
cin>>n;
s1.init(5);
cout<<"输入要插入的数据"<<endl;
for(int i=0;i<5;i++)
{
string s;
cin>>s;
int e=stoi(s);
s1.push_back(e);
}
s1.show();
int add;
cout<<"输入要插入的位置" ;
getchar();
cin>>add;
s1.insert(add);
s1.show();
cout<<"输入要删除的位置";
cin>>add;
s1.delete_s(add);
s1.show();
int c;
cout<<"是否尾删(1为yes/2为no)";
cin>>c;
if(c==1)
{
s1.pop_back();
}
s1.show();
int changdu=s1.get_len();
cout<<"顺序表长度为"<<changdu<<endl;
int index;
cout<<"输入要查找位置的元素";
cin>>index;
cout<<index<<"元素"<<s1.get_index(index)<<endl;
cout<<"(输入1为升序排序/2为降序排序)";
cin>>c;
s1.sort(c);
s1.show();
return 0;
}