您的位置:首页 > 编程语言 > C语言/C++

线性表顺序存储结构的C++模板类程序源代码

2016-05-31 18:22 399 查看
线性表顺序存储结构说白了就是数组,类定义了两个成员变量:一个足够大的数组和元素个数变量。下面是自己写的一个线性表类,可以直接使用或增加成员函数使用。

#ifndef LINEARLIST_H
#define LINEARLIST_H
#include <iostream>
const int MAXSIZE=100;
template<typename ElementType>
class LinearList
{
private:
ElementType Data[MAXSIZE];
int last;
public:
LinearList();
~LinearList(){
}
int Find(ElementType);
void Insert(int ,ElementType);
void Delete(int);
bool IsEmpty();
bool IsFull();
void Print();
ElementType operator[](int);
};

template<typename ElementType>
LinearList<ElementType>::LinearList():last(-1)
{
}
template<typename ElementType>
int LinearList<ElementType>::Find(ElementType x)
{
for(int i=0;i<=last;i++)
{
if(Data[i]==x)
{
std::cout<<"We find the element "<<x<<" that you search, it is at NO." <<i<<" position !"<<std::endl;
return i;
}
}
std::cout<<"We did not find the element that you search!"<<std::endl;
return -1;
}
template<typename ElementType>
void LinearList<ElementType>::Insert(int i ,ElementType x)
{
if(IsFull())
{
std::cout<<"The List is full now!";
return;
}
for(int j=last;j>=i;j--)
{
Data[j+1]=Data[j];
}
Data[i]=x;
last++;
return;
}
template<typename ElementType>
void LinearList<ElementType>::Delete(int i)
{
if(IsEmpty())
{
std::cout<<"The List is empty now!"<<std::endl;
return;
}
if(i>last+1)
{
std::cout<<"The element you delete is out of the list!"<<std::endl;
return;
}
for(int j=i;j<last;j++)
{
Data[j]=Data[j+1];
}
last--;
return;
}
template<typename ElementType>
bool LinearList<ElementType>::IsEmpty()
{
if(last==-1)
return true;
else
return false;
}
template<typename ElementType>
bool LinearList<ElementType>::IsFull()
{
if(last==MAXSIZE)
return true;
else
return false;
}
template<typename ElementType>
void LinearList<ElementType>::Print()
{
std::cout<<"The list is printed in the next:\n";
for(int i=0;i<=last;i++)
{
std::cout<<Data[i]<<" ";
}
std::cout<<std::endl;
}
template<typename ElementType>
ElementType LinearList<ElementType>::operator[](int i)
{
return Data[i];
}
#endif


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息