#include <iostream>
#include <cstring>
using namespace std;
#include <iostream>
using namespace std;
template<typename T1,typename T2>
class List{
public:
T1 len;
T2 arr[20];
List(){}
// List &operator=(const List &other)
// {
// len=other.len;
// strcpy(arr,other.arr);
// return *this;
// }
};
template<typename T1,typename T2>
List<T1,T2> init(List<T1,T2> &list)
{
list.len=0;
memset(list.arr,0,sizeof(list.arr));
return list;
};
//尾插
template<typename T1,typename T2>
List<T1,T2> insertRear(List<T1,T2> &list,T2 data)
{
if(list.len>=20)
throw new int(1);
list.arr[list.len++]=data;
return list;
};
//指定位置插入元素
template<typename T1,typename T2>
void inserLocation(List<T1,T2> &list,T1 index,T2 data)
{
if(index<0 || index >list.len)
throw new int(2);
for (int i=list.len;i>index;i--) {
list.arr[i]=list.arr[i-1];
}
list.len++;
list.arr[index]=data;
}
//指定位置删除元素
template<typename T1,typename T2>
void deleteLocation(List<T1,T2> &list,T1 index)
{
if(index<0 || index >=list.len || list.len<=0)
throw new int(3);
for (int i=index;i<list.len-1;i++) {
list.arr[i]=list.arr[i+1];
}
list.len--;
}
//查找值的位置
template<typename T1,typename T2>
int searchLocation(List<T1,T2> &list,T2 element)
{
for (int i=0;i<list.len;i++) {
if(list.arr[i]==element)
{
return i;
break;
}
}
throw new int(4);
return 0;
}
//按照值删除元素
template<typename T1,typename T2>
void deleteElement(List<T1,T2> &list,T2 element)
{
int index=searchLocation<T1,T2>(list,element);
deleteLocation<T1,T2>(list,index);
}
//打印顺序表
template<typename T1,typename T2>
void show(List<T1,T2> &list)
{
cout << "列表数据为:" << endl;
for (int i=0;i<list.len;i++) {
cout << list.arr[i] << "\t";
}
cout << "" << endl;
};
int main(){
//初始化顺序表
List<int,char> list;
init(list);
try {
//尾插赋值列表
cout << "请输入您要插入的元素,以字符'#'结束";
int a;
int count=1;
char element;
while(1)
{
cout << "请输入第" << count << "个字符" << endl;
cin>>element;
if(element == '#')
break;
count++;
insertRear<int,char>(list,element);
}
show<int,char>(list);
cout <<"-----------------------------"<<endl;
//插入指定位置元素
int index;
cout << "请输入您要插入的元素位置" << endl;
cin>>index;
cout << "请输入您要插入字符值" << endl;
cin >>element;
inserLocation<int,char>(list,index-1,element);
show<int,char>(list);
cout <<"-----------------------------"<<endl;
//删除指定位置元素
cout << "请输入您要删除的元素位置" << endl;
cin>>index;
deleteLocation<int,char>(list,index-1);
show<int,char>(list);
cout <<"-----------------------------"<<endl;
//查找指定值的位置
cout<<"请输入您要查找的值" <<endl;
cin >> element;
index=searchLocation<int,char>(list,element);
cout << "位置在第" << index+1 << "个" << endl;
//按照值删除元素
cout << "请输入您要删除的值" << endl;
cin >>element;
deleteElement<int,char>(list,element);
show<int,char>(list);
} catch (int i) {
if(i==1){
cout << "列表已满,无法插入" <<endl;
}
if(i==2){
cout << "插入位置异常" <<endl;
}
if(i==3){
cout << "删除位置异常" <<endl;
}
if(i==4){
cout << "无法找到对应的值" <<endl;
}
}
}
}