最近准备找工作了,在复习数据结构,下面是用C++写的顺序表的一个类(头文件)
//公元2013年3月15日
//Sequence List--By Paul
#ifndef _SeqList_
#define _SeqList_
const int defaultSize=100;
template <typename Type> class SeqList{
public:
SeqList(int SZ=defaultSize):m_nmaxsize(SZ),m_ncurrentsize(-1){
if (SZ>0){
m_elements=new Type[m_nmaxsize];
}
}
~SeqList(){
delete[] m_elements;
}
int Length() const{
return m_ncurrentsize+1;
}
int Find(Type x) const;
int IsElement(Type x) const;
int Insert(Type x,int i);
int Remove(Type x);
int IsEmpty(){
return m_ncurrentsize==-1;
}
int IsFull()
{
return m_ncurrentsize==m_nmaxsize-1;
}
Type Get(int i){
return i<0||i>m_ncurrentsize?(cout<<"can't find the element"<<endl,0):m_element[i];
}
void Print();
private:
Type *m_element;
const int m_nmaxsize;
int m_ncurrentsize;
};
//部分函数的实现。。。。。
template <typename Type> int SeqList<Type>::Find(Type x) const
{
for(int i=0;i<m_ncurrentsize;i++)
{
if(m_element[i]==x)
return i;
}
cout<<"Can't find the element you want to find"<<endl;
return -1;
}
template <typename Type> int SeqList<Type>::IsElement(Type x) const
{
if(Find(X)==-1)
return 0;
return 1;
}
template <typename Type> int SeqList<Type>::Insert(Type x,int i)
{
if(i<0||i>mm_ncurrentsize+1||m_ncurrentsize==m_nmaxsize-1)
{
cout<<"The operation is illegal"<<endl;
return 0;
}
m_ncurrentsize++;
for(int j=m_ncurrentsize;j>i;j--)
{
m_element[j]=m_element[j-1];
}
m_element[i]=x;
return 1;
}
template <typename Type> int SeqList<Type>::Remove(Type x){
int size=m_ncurrentsize;
for(int i=0;i<m_ncurrentsize;){
if(m_elements[i]==x){
for(int j=i;j<m_ncurrentsize;j++){
m_element[j]=m_elements[j+1];
}
m_ncurrentsize--;
continue;
}
i++;
}
if(size==m_ncurrentsize){
cout<<"can't find the element you want to remove"<<endl;
return 0;
}
return 1;
}
template <typename Type> void SeqList<Type>::Print(){
for(int i=0;i<=m_ncurrentsize;i++)
cout<<i+1<<":\t"<<m_element[i]<<endl;
cout<<endl<<endl;
}
#endif
(好像很久没写C++的代码了,比较生疏了,慢慢写,慢慢熟悉)