1.用模板类写顺序表
#include <iostream>using namespace std;#define MAXSIZE 10
template <typename T>
class Arr
{T *data =NULL;int len = 0;
public://构造函数Arr():data(new T){}Arr(T a,int len):data(new T(a)),len(len){}//析构函数~Arr(){delete data;}//向顺序表尾插元素void insert_data(Arr &a1,T a);//删除顺序尾删元素void delete_data(Arr &a1);//按照指定值查找元素int search_data(Arr &a1,T a);//遍历void output(Arr a1);};//尾插
template <typename T>
void Arr<T>::insert_data(Arr &a1,T a)
{//判满以及堆区地址是否创建if(a1.len == MAXSIZE || data == NULL){return;}//尾插数据*(a1.data+a1.len) = a;a1.len++;
}
//尾删
template <typename T>
void Arr<T>::delete_data(Arr &a1)
{//判空if(a1.len == 0){return;}//尾删a1.len--;
}
//按照指定值查找元素,返回index下标
template <typename T>
int Arr<T>::search_data(Arr &a1,T a)
{//判空if(a1.len == 0){return -1;}//查找for(int index=0;index<len;index++){if(*(a1.data+index) == a){return index;}}return -1;
}
//遍历
template <typename T>
void Arr<T>::output(Arr a1)
{//判空if(a1.len == 0){return;}for(int i=0; i<len ;i++){cout << *(a1.data+i) << "\t";}cout << endl;
}int main()
{Arr<int> a1;cout << "头插数据:" << endl;a1.insert_data(a1,1);a1.insert_data(a1,2);a1.insert_data(a1,3);a1.insert_data(a1,4);a1.insert_data(a1,5);cout << "遍历结果:" << endl;a1.output(a1);cout << "尾删数据:" << endl;a1.delete_data(a1);cout << "遍历结果:" << endl;a1.output(a1);cout << "查找元素:" << endl;int index = a1.search_data(a1,3);if(index == -1){cout << "查找元素不存在" << endl;}else {cout << "下标为: " << index << endl;}return 0;
}
2.思维导图