#include <iostream>
using namespace std;
const int max_size = 200;
template<typename T>
class Linear_table
{
public:
Linear_table(){length = 0;}
Linear_table(T a[], size_t n);
~Linear_table(){}
//线性表长度
size_t size();
//是否为空
bool empty();
//获取元素
T get(size_t);
//插入元素
void insert(size_t, T);
//删除元素
void remove(size_t);
//查询元素
size_t find(T);
//遍历
void print();
private:
T SeqList[max_size];
size_t length = 0;
};
int main(int argc, char *argv[])
{
Linear_table<int> l_t;
l_t.insert(0, 8);
l_t.insert(1, 5);
l_t.insert(2, 6);
l_t.insert(3, 2);
l_t.insert(4, 45);
size_t mark = l_t.find(2);
cout<<"find the mark:"<<mark<<endl;
cout<<l_t.get(1)<<endl;
cout<<l_t.size()<<endl;
l_t.remove(1);
cout<<"-----------------------"<<endl;
bool ok = l_t.empty();
if(!ok)
l_t.print();
else
cout<<"the list is empty!"<<endl;
return 0;
}
template<typename T>
Linear_table<T>::Linear_table(T a[], size_t n)
{
if(n > max_size)
throw "the 'n' error!";
for(size_t i = 0; i < n; ++n)
SeqList[i] = a[i];
length = n;
}
template<typename T>
size_t Linear_table<T>::size()
{
return length;
}
template<typename T>
bool Linear_table<T>::empty()
{
if(length == 0)
return true;
else
return false;
}
template<typename T>
T Linear_table<T>::get(size_t sz)
{
return SeqList[sz];
}
template<typename T>
void Linear_table<T>::insert(size_t sz, T e)
{
int k;
if(sz < 0 || sz > this->length)
throw "add location is error!";
if(this->length == max_size)
throw "add location is overflow!";
if(sz <= this->length && sz != 0)
{
for(k =this->length; k > sz - 1; --k)
SeqList[k+1] = SeqList[k];
}
if(sz == 0)
SeqList[0] = e;
else
SeqList[k+1] = e;
this->length++;
}
template<typename T>
void Linear_table<T>::remove(size_t sz)
{
int k;
if(sz < 0 || sz > this->length - 1)
throw "remove location is error!";
if(sz <= this->length - 1)
{
for(k = sz; k < this->length; ++k)
SeqList[k] = SeqList[k+1];
}
this->length--;
}
template<typename T>
size_t Linear_table<T>::find(T t)
{
for(size_t k = 0; k < length; ++k)
{
if(t == SeqList[k])
return k;
}
return -1;
}
template<typename T>
void Linear_table<T>::print()
{
for(int i = 0; i < length; i++)
cout<<SeqList[i]<<endl;
}
数据结构c++实现——线性表的顺序结构
最新推荐文章于 2022-10-19 21:07:09 发布