标签:
/****************************
* Date : 2015-07-19
* Description: LinerList.h
*****************************/
#ifndef _LINER_LIST_H
#define _LINER_LIST_H
//
#include <iostream>
//class LinerList
template<class T>
class LinerList
{
public:
// 创建一个线性表(默认构造函数)
LinerList(int MaxListSize = 10);
// 删除表(析构函数)
~LinerList() { delete [] element;}
//如果表为空则返回true,否则返回false
bool IsEmpty() const {return length == 0;}
//返回表的大小(即表中元素的个数)
int Length() const {return length;}
//查找表中第k个元素,并把它保存到x中;如果不存在,则返回false
bool Find(int k, T& x) const;
//返回元素x在表中的位置;如果x不在表中,则返回0
int Search(const T& x) const;
//删除第k个元素,并把它保存到x中;函数返回修改后的线性表
LinerList<T>& Delete(int k, T& x);
//在第k个元素之后插入x;函数返回修改后的线性表
LinerList<T>& Insert(int k, const T& x);
// 元素输出
void Output(std::ostream& os) const;
private:
int length; // 表中元素个数
int MaxSize; // 表的容量
T *element; // 一维动态数组
};
// << 重载
template<class T>
std::ostream& operator<<(std::ostream &, const LinerList<T> &);
#include "LinerList.cpp"
#endif // _LINER_LIST_H
/****************************
* Date : 2015-07-19
* Description: LinerList.cpp
*****************************/
#ifndef _LINER_LIST_CPP
#define _LINER_LIST_CPP
#include "LinerList.h"
//#include <iostream>
//template<class T> class LinerList;
//
template<class T>
void LinerList<T>::Output(std::ostream& os) const
{
for(int i = 0; i < length; i++)
os << element[i] << " ";
}
//
template<class T>
std::ostream& operator<<(std::ostream& os, const LinerList<T>& List)
{
List.Output(os);
return os;
}
//
template<class T>
LinerList<T>::LinerList(int MaxListSize = 10)
{
MaxSize = MaxListSize;
element = new T[MaxSize];
length = 0;
}
//
template<class T>
bool LinerList<T>::Find(int k, T& x) const
{
if(k < 1 || k > length)
return false;
x = element[k-1];
return true;
}
//
template<class T>
int LinerList<T>::Search(const T& x) const
{
for(int i = 0; i < length; i++)
if(element[i] == x)
return ++i;
return 0;
}
//
template<class T>
LinerList<T>& LinerList<T>::Delete(int k, T &x)
{
if(Find(k, x))
{
for(int i = k; i < length; i++)
element[i-1] = element[i];
length--;
return *this;
}
else
{
cerr << "out of bounds" << endl;
exit(EXIT_FAILURE);
}
}
//
template<class T>
LinerList<T>& LinerList<T>::Insert(int k, const T &x)
{
if(k < 0 || k > length)
{
cerr << "out of bounds" << endl;
exit(EXIT_FAILURE);
}
if (length == MaxSize)
{
//cerr << "no enough space" << endl;
//exit(EXIT_FAILURE);
// 存储加倍
MaxSize *= 2;
T *new_element = new T[MaxSize];
for(int i = 0; i < length; i++)
new_element[i] = element[i];
delete [] element;
element = new_element;
}
for(int i = length-1; i >= k; i--)
element[i+1] = element[i];
element[k] = x;
length++;
return *this;
}
#endif // _LINER_LIST_CPP
标签:
原文地址:http://www.cnblogs.com/hzwackerman/p/4659471.html