在顺序存储结构实现基本操作:初始化、创建、插入、删除、查找、遍历、逆置、合并运算
#include <iostream>
#include <cstdlib>
using namespace std;
template<typename T>
class SeqList
{
private:
T* data;
int maxSize;
int last;
void Resize(int newSize)
{
T *newAry;
if(newSize<=0)
{
cerr<<"无效的数组大小"<<endl;
return;
}
if(newSize!=maxSize)
{
newAry=new T[newSize];
if(newAry==NULL)
{
cerr<<"存储分配错误"<<endl;
exit(1);
}
int n=last+1;
T* srcptr=data;
T* desptr=newAry;
while(n--)
{
*desptr++=*srcptr++;
}
delete [] data;
data=newAry;
maxSize=newSize;
}
}
public:
SeqList(int sz=0)
{
maxSize=sz;
last=sz-1;
data=new T[maxSize];
}
SeqList(SeqList<T> &L)
{
maxSize=L.maxSize;
last=L.last;
data=new T[maxSize];
if(data==NULL)
{
cerr<<"存储分配失败"<<endl;
exit(1);
}
for(int i=0;i<last;i++)
{
data[i]=L.data[i];
}
}
~SeqList()
{
delete []data;
}
int Size()const
{
return maxSize;
}
int Length()const
{
return last+1;
}
int Search(const T &x)const
{
for(int i=0;i<=last;i++)
{
if(data[i]==x)
{
return i+1;
}
}
return 0;
}
int Locate(int i)const
{
if(i>=1 && i<=last+1)
{
return i;
}
else
return 0;
}
bool GetData(int i, T &x)const
{
if(Locate(i))
{
x=data[i-1];
return true;
}
else
{
return false;
}
}
void SetData(int i,T& x)
{
if(Locate(i))
{
data[i-1]=x;
}
}
bool IsEmpty()const
{
return last==-1;
}
bool IsFull()const
{
return last==maxSize-1;
}
bool Insert(const T &x,int i)
{
if(i<1 || i>last+2)
{
return false;
}
for(int j=last;j>=i-1;j--)
{
data[j+1]=data[j];
}
maxSize++;
data[i-1]=x;
last++;
return true;
}
bool Remove(int i,T &x)
{
if(last==-1)
{
return false;
}
if(!Locate(i))
{
return false;
}
x=data[i-1];
for(int j=i-1;j<last;j++)
{
data[j]=data[j+1];
}
last--;
return true;
}
void Sort()
{
if(last==-1)
{
return;
}
for(int i=0;i<=last;i++)
{
for(int j=0;j<=last;j++)
{
if(data[i]<data[j])
{
T temp;
temp=data[i];
data[i]=data[j];
data[j]=temp;
}
}
}
}
void Input()
{
if(last==-1)
{
return;
}
for(int i=0;i<=last;i++)
{
cin>>data[i];
}
}
void Output()
{
int i;
if(last==-1)
{
return;
}
for(i=0;i<=last;i++)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
void MakeEmpty()
{
last=-1;
}
void Reverse()
{
for(int i=0;i<Length()/2;i++)
{
T temp;
temp=data[i];
data[i]=data[Length()-i-1];
data[Length()-i-1]=temp;
}
}
};
int main()
{
int m,n;
cin>>m;
SeqList<int> a(m);
a.Input();
int x,y;
cin>>x>>y;
a.Insert(x,y);
a.Output();
int index,num;
cin>>index;
a.Remove(index,num);
a.Output();
int z,f;
cin>>z;
f=a.Search(z);
if(f==0)
{
cout<<"Not found"<<endl;
}
else
{cout<<a.Search(z)<<endl;}
a.Reverse();
a.Output();
int mm;
cin>>mm;
SeqList<int> b(mm);
SeqList<int> c(mm+m);
b.Input();
for(int i=0;i<a.Length();i++)
{
int temp;
a.GetData(i+1,temp);
c.SetData(i+1,temp);
}
for(int i=a.Length();i<(a.Length()+b.Length());i++)
{
int temp;
b.GetData(i-a.Length()+1,temp);
c.SetData(i+1,temp);
}
c.Sort();
c.Output();
return 0;
}