?? 順序表類模板.cpp
字號:
#include<iostream.h>
#define NULL 0
template<typename T,int size>class seqlist{
T slist[size];
int M;
int last;
public:
seqlist(){
last=-1;M=size;}
int Length()const{return last+1;}
int Find(T&x)const;
bool IsIn(T&x);
bool Insert(T&x,int i);
bool Remove(T&x);
int Next(T&x);
int Prior(T&x);
bool IsEmpty(){return last==-1;}
bool IsFull(){return last==M-1;}
T Get(int i){return i<0||i>last? NULL:slist[i];}
};
template<typename T,int size>int seqlist<T,size>::Find(T&x)const{
int i=0;
while(i<=last&&slist[i]!=x)i++;
if(i>last)return -1;
else return i;
}
template<typename T,int size>bool seqlist<T,size>::IsIn(T&x){
int i=0;
bool found =0;
while(i<=last&&!found)
if(slist[i]!=x)i++;
else found=1;
return found;
}
template<typename T,int size>bool seqlist<T,size>::Insert(T&x,int i){
if(i<0||i>last+1||last==M-1)return false;
else{
last++;
for(int j=last;j>i;j--)slist[j]=slist[j-1];
slist[i]=x;
return true;
}
}
template<typename T,int size>bool seqlist<T,size>::Remove(T&x){
int i=Find(x);
if(i>=0){
last--;
for(int j=i;j<=last;j++)slist[j]=slist[j+1];
return true;
}
return false;
}
template<typename T,int size>int seqlist<T,size>::Next(T&x){
int i=Find(x);
if(i>=0&&i<last)return i+1;
else return -1;
}
template<typename T,int size>int seqlist<T,size>::Prior(T&x){
int i=Find(x);
if(i>0&&i<=last)return i-1;
else return -1;
}
void main(){
seqlist<int,100>seqlisti;
int i,j,k,a[10]={2,3,5,7,11,13,17,19,23,29};
for(j=0;j<10;j++)if(!seqlisti.Insert(a[j],j)){
cout<<"表太大放不下了!"<<endl;
break;
}
j=seqlisti.Length();
cout<<j;
for(i=0;i<j;i++)cout<<seqlisti.Get(i)<<' ';
cout<<endl;
k=7;
if(seqlisti.IsIn(k))cout<<"素數7在順序表中"<<endl;
else cout<<"素數7不在順序表中"<<endl;
k=17;
if(seqlisti.Remove(k))cout<<"刪除素數17 "<<endl;
else cout<<"找不到素數7 "<<endl;
j=seqlisti.Length();
for(i=0;i<j;i++)cout<<seqlisti.Get(i)<<' ';
cout<<endl;
if(seqlisti.Insert(k,j-1)){
j=seqlisti.Length();
for(int i=0;i<j;i++)cout<<seqlisti.Get(i)<<' ';
cout<<endl;
}
cout<<"打印17后的一個素數:"<<seqlisti.Get(seqlisti.Next(k))<<endl;
cout<<"打印17前的一個素數:"<<seqlisti.Get(seqlisti.Prior(k))<<endl;
cout<<"素數17在表中的位置(下標):"<<seqlisti.Find(k)<<endl;
if(seqlisti.IsEmpty())cout<<"表是空的"<<endl;
else cout<<"表不空"<<endl;
if(seqlisti.IsFull())cout<<"表是滿的"<<endl;
else cout<<"表也不滿"<<endl;
if(seqlisti.IsIn(k))cout<<"素數17在表中"<<endl;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -