一个线性表的类:
1 #include <fstream> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdlib> 5 6 using namespace std; 7 8 #define N 100 9 enum Status{success,fail,fatal,range_error,overflow}; 10 11 class List{ 12 private: 13 char *list; 14 int len; 15 16 public: 17 List(char *tlist=""){ 18 list=new char[N]; 19 strcpy(list,tlist);//初始化 20 len=strlen(list); 21 } 22 ~List(){ 23 delete list; 24 } 25 void listClear(){//销毁 26 list[0]='\0'; 27 len=0; 28 } 29 bool listEmpty(){//判空 30 return len==0; 31 } 32 int listSize(){//求长度 33 return len; 34 } 35 Status listRetrieve(int pos,char &elem){//取指定位置元素 36 if(pos>=0&&pos<len){ 37 elem=list[pos]; 38 return success; 39 }else return range_error; 40 } 41 Status listLocate(char elem,int &pos);//按值查找 42 Status listInsert(int pos,char elem);//插入 43 Status listRemove(int pos);//删除 44 Status listPrior(int pos,char &elem);//求前驱 45 Status listNext(int pos,char &elem);//求后继 46 }; 47 48 int main(){ 49 //freopen("D:\\input.in","r",stdin); 50 //freopen("D:\\output.out","w",stdout); 51 52 return 0; 53 } 54 Status List::listLocate(char elem,int &pos){ 55 for(int i=0;i<len;i++){ 56 if(list[i]==elem){ 57 pos=i; 58 return success; 59 } 60 } 61 return fail; 62 } 63 Status List::listInsert(int pos,char elem){ 64 if(len==N) return overflow; 65 if(pos<0||pos>len) return range_error; 66 for(int i=len;i>pos;i--) list[i]=list[i-1]; 67 list[pos]=elem; 68 len++; 69 return success; 70 } 71 Status List::listRemove(int pos){ 72 if(pos<0||pos>=len) return range_error; 73 for(int i=pos;i<len-1;i++) list[i]=list[i+1]; 74 len--; 75 return success; 76 } 77 Status List::listPrior(int pos,char &elem){ 78 return listRetrieve(pos-1,elem); 79 } 80 Status List::listNext(int pos,char &elem){ 81 return listRetrieve(pos+1,elem); 82 }