#include<iostream> #include "stdlib.h" using namespace std; const int DefaultSize=100; template<class T> class SeqList{ public: T *data; int maxSize; int last; void reSize(int newSize); SeqList(int sz=DefaultSize); ~SeqList(){ delete[] data; } int Size(){ return maxSize; } int Length(){ return last+1; } int Search(T x); void setData(int i,T x){ if(i>0&&i<=last+1) data[i-1]=x; } bool Insert(int i,T x); bool Remove(int i,T x); bool IsEmpty(){ return(last==-1)?true:false; } bool IsFull(){ return(last==maxSize-1)?true:false; } void output(); }; template <class T> SeqList<T>::SeqList(int sz){ if(sz>0){ maxSize=sz; last=-1; data=new T[maxSize]; if(data==NULL){ cerr<<"存储分配失误!"<<endl; exit(1); } } } template<class T> void SeqList<T>::reSize(int newSize){ if(newSize<=0){ cerr<<"无效的数组大小"<<endl; return; } if(newSize!=maxSize){ T *newarray=new T[maxSize]; if(newarray==NULL){ cerr<<"存储分配错误"<<endl; exit(1); } int n=last+1; T * srcptr=data; T * destptr=newarray; while(n--) * destptr++=* srcptr++; delete[]data; data=newarray; maxSize=newSize; } } template<class T> int SeqList<T>::Search(T x){ for(int i=0;i<=last;i++){ if(data[i]==x) return i+1; } return 0; } template<class T> bool SeqList<T>::Insert(int i,T x){ if(last==maxSize-1) return false; if(i<0||i>last+1) return false; for(int j=last;j>=i;j--) data[j+1]=data[j]; data[i]=x; last++; return true; } template<class T> bool SeqList<T>::Remove(int i,T x){ if(last==-1) return false; if(i<1||i>last+1) return false; x=data[x-1]; for(int j=i;j<last;j++) data[j-1]=data[j]; last--; return true; } template<class T> void SeqList<T>::output(){ cout<<"顺序表当前元素最后位置为:"<<last<<endl; for(int i=0;i<=last;i++){ cout<<"#"<<i+1<<":"<<data[i]<<endl; } } void main(){ SeqList<int> seqList(10); int array[10]={1,2,3,4,5,6,7,8,9,10}; for(int i=0;i<10;i++){ seqList.Insert(i,array[i]); } seqList.reSize(11); seqList.Insert(2,100); seqList.output(); seqList.Remove(10,10); seqList.setData(1,99); seqList.output(); cout<<seqList.Search(100); }
自己敲的,参考教材《数据结构(第二版)》殷人昆 著,都是些简单的实现,不要见笑了。到5月底更新算法分析与设计。
运行截图:
原文链接:https://www.f2er.com/datastructure/383124.html