数据结构顺序表的增删查改

2018-1-5 hwd C/C++

const int MaxSize=100;  
template <class T> //模板类  
class SeqList  
{  
public:  
SeqList() {length=0;} //无参构造函数  
SeqList(T a[],int n); //有参构造函数  
~SeqList(){} //析构函数  
int Length() {return length;} //求线性表长度  
T Get(int i); //按位查找  
int Locate(T x); //按值查找  
void Insert (int i, T x); // 插入函数  
T Delete(int i); //删除函数  
void PrintList(); //遍历线性表,按序号依次输出各个元素。  
private:  
T data[MaxSize];  
int length;  
};  
template<class T>  
SeqList<T>::SeqList(T a[],int n) //有参构造函数  
{  
if(n>MaxSize)throw"参数非法";  
for(int i=0;i<n;i++)  
data[i]=a[i];  
length=n;  
}  
template <class T>  
void SeqList<T>::Insert(int i,T x) //插入函数  
{  
if (length>=MaxSize) throw "上溢";  
if(i<1||i>length+1) throw "位置异常";  
//请补全代码  
for(int j=length;j>=i;j--)  
data[i-1]=x;  
length++;  
}  
template <class T>  
T SeqList<T>::Get(int i) //按位查找函数  
{  
if(i<1||i>length) throw "查找位置非法";  
else   
return data[i-1];  
}  
template <class T>  
int SeqList<T>::Locate(T x) //按值查找函数  
{  
for(int i=0;i<length;i++)  
if(data[i]=x)  
return i+1;  
}  
template <class T>  
T SeqList<T>::Delete(int i) //删除函数  
{  
if (int length=0)throw "下溢";  
if(i<1||i>length)throw "位置异常";  
for(i=0;i<length;i++)  
data[i-1]=data[i];  
length--;  
return i;  
}  
template<class T>  
void SeqList<T>::PrintList() // 遍历线性表  
{  
for(int i=0;i<length;i++)  
{  
cout<<data[i];  
}

}


#include <iostream>  
#include "SeqList.h"  
using namespace std;  
void menu()  
{  
cout<<" 欢迎,欢迎!"<<endl;  
cout<<" 1.插入查询"<<endl;  
cout<<" 2.删除函数"<<endl;  
cout<<" 3.求表长"<<endl;  
cout<<" 4.按值查找"<<endl;  
cout<<" 5.按位查找"<<endl;  
cout<<" 6.遍历线性表"<<endl;  
cout<<" 7.退出"<<endl;  
cout<<" "<<endl;  
cout<<" 请选择编号:"<<endl;  
}  
int main()  
{  
int i,j,x;  
int a[7]={12,15,24,56,67,68,86};  
SeqList<int> s1(a,7);  
int flag=1;  
while(flag)  
{  
menu();  
cin>>j;  
switch(j)  
{  
case 1:  
{  
try  
{  
cout<<"显示要插入的位序及数值:"<<endl;  
cin>>i>>x;  
cout<<endl;  
s1.Insert(i,x);  
s1.PrintList();  
}  
catch (char *s){cout<<s<<endl;}  
};  
break;  
case 2:  
{  
try  
{  
cout<<"输入元素所在位置";  
cin>>i;  
x=s1.Delete(i);  
cout<<"已删除:"<<x<<endl;  
cout<<"删除数据后表变为:"<<endl;  
s1.PrintList();  
}  
catch (char *s){cout<<s<<endl;}  
};  
break;  
case 3:  
{  
try   
{  
s1.Length();  
cout<<"线性表长度为:"<<s1.Length()<<endl;  
}  
catch(char *s){cout<<s<<endl;}  
};  
break;  
case 4:  
{  
try  
{  
cout<<"输入查找数据x:"<<endl;  
cin>>x;  
s1.Locate(x);  
cout<<"所查数据在第"<<s1.Locate(x)<<"位"<<endl;  
}  
catch(char *s){cout<<s<<endl;}  
};  
break;  
case 5:  
{  
try  
{  
cout<<"查找位置i=";  
cin>>i;  
s1.Get(i);  
cout<<"该位置元素为:"<<s1.Get(i)<<endl;  
}  
catch(char *s){cout<<s<<endl;}  
};  
break;  
case 6:  
{  
try  
{  
s1.PrintList();  
}  
catch(char *s){cout<<s<<endl;}  
};  
break;  
case 7:  
flag=0;  
break;  
default:cout<<"错误!!!"<<endl;  
break;  
}  
}  
return 0;  
}  

评论(0) 浏览(254)


hwdmn by hwdmn 赣ICP备18000235号-1

赣公网安备 36072302000196号