顺序表
数据结构顺序表,注意输入的i值是指数组的下标还是实际位于第几个。
代码
#include <iostream>
#include <cstdlib>
using namespace std;
template<class T>
class seqlist
{
protected:
int maxsize;
T *data;
int last;
void Resize(int newsize);
public:
seqlist(int sz);
seqlist(seqlist<T> &L);
int Search(T &x);
int Locate(int i);
bool Insert(int i,T& x);
bool Remove(int i,T&x);
void output();
void input();
friend void Union(seqlist<int> &A,seqlist<int> &B);
friend void intersection(seqlist<int> &A,seqlist<int> &B);
};
template<class T>
seqlist<T>::seqlist(int sz)
{
maxsize=sz;
data=new T[sz];
last=-1;
if(data==NULL)
{
cerr<<"错误"<<endl;
exit(1);
}
}
template<class T>
seqlist<T>::seqlist(seqlist<T> &L)
{
maxsize=L.maxsize;
data=new T[maxsize];
last=L.last;
for(int i=0; i<=last; i++)
data[i]=L.data[i];
}
template<class T>
void seqlist<T>::Resize(int newsize)
{
if(newsize<=0)
{
cerr<<"错误"<<endl;
return;
}
if(newsize!=maxsize)
{
T* newarry=new T[newsize];
if(newarry==NULL)
{
cerr<<"错误"<<endl;
exit(1);
}
int n=last+1;
T* srcptr=data;
T* destptr=newarry;
while(n--) *destptr++=*srcptr++;
delete []data;
data=newarry;
maxsize=newsize;
}
}
template<class T>
int seqlist<T>::Search(T &x)
{
for(int i=0; i<last+1; i++)
if(data[i]==x)
return i+1;
return 0;
}
template<class T>
int seqlist<T>::Locate(int i)
{
if(i>=1&&i<=last+1) return i;
else return 0;
}
template<class T>
bool seqlist<T>::Insert(int i,T&x)
{
if(i<1||i>last+2) return false;
if(last==maxsize-1) return false;
for(int j=last; j>=i-1; j--)
data[j+1]=data[j];
data[i-1]=x;
last++;
return true;
}
template<class T>
bool seqlist<T>::Remove(int i,T&x)
{
if(i<1||i>last+2) return false;
if(last==-1) return false;
x=data[i-1];
for(int j=i; j<=last; j++)
data[j-1]=data[j];
last--;
return true;
}
template<class T>
void seqlist<T>::input()
{
cout<<"开始建立顺序表,请输入表中个数";
while(1)
{
cin>>last;
last--;
if(last<=maxsize-1)
break;
cout<<"表元素个数输入有误,范围不能超过"<<maxsize-1<<":";
}
for(int i=0; i<=last; i++)
{
cin>>data[i];
cout<<i+1<<endl;
}
};
template<class T>
void seqlist<T>::output()
{
cout<<"顺序表当前元素最后位置为:"<<last+1<<endl;
for(int i=0; i<=last; i++)
cout<<"#"<<i+1<<":"<<data[i]<<endl;
};
void Union(seqlist<int> &A,seqlist<int> &B)
{
for(int i=0; i<=B.last; i++)
{
if(A.Search(B.data[i])==0)
A.Insert(A.last+2,B.data[i]);
}
}
void intersection(seqlist<int> &A,seqlist<int> &B)
{
int x;
for(int i=0; i<=A.last; i++)
{
if(B.Search(A.data[i])==0)
A.Remove(i+1,x);
}
}
int main()
{
/*seqlist<int> pp1(10);
seqlist<int> pp2(10);
pp1.input();
pp2.input();
intersection(pp1,pp2);
pp1.output();*/
return 0;
}