//来自数据结构书本的示例代码,编译器为VS2008
//类的声明与定义头文件LinearList.h
#ifndef _LinearList_h
#define _LinearList_h
#include <iostream>
#include "xcept.h"
using namespace std;
template<class T> class LinearList{
public:
LinearList(int MaxListSize = 10);
~LinearList(){
delete [] element;
}
bool IsEempty() const{ //检查表是否为空
return length == 0;
}
int Length() const{ //返回表的大小,即表中元素个数
return length;
}
bool Find(int k, T& x) const; //把第k个元素取至x中,如果不存在第k个元素则返回false,否则返回true
int Search(const T& x) const; //查找x,如果找到,则返回x所在的位置,如果x不在表中,则返回0
LinearList<T>& Delete(int k, T& x); //把第k个元素放到x中,然后删除第k个元素,如果不存在第k个元素,则引发异常OutOfBounds
LinearList<T>& Insert(int k, const T& x); //在第k个元素之后插入x,如果不存在第k个元素,则引发异常OutOfBounds,如果表已满,则引发异常NoMem
void Output(ostream& out) const;
private:
int length;
int MaxSize;
T* element;
};
template<class T> LinearList<T>::LinearList(int MaxListSize){
MaxSize = MaxListSize;
element = new T[MaxSize];
length = 0;
}
template<class T> bool LinearList<T>::Find(int k, T &x) const{
if (k < 1 || k > length) //不存在第k个元素
return false;
x = element[k - 1];
return true;
}
template<class T> int LinearList<T>::Search(const T& x) const{
for (int i = 0; i < length; i++)
if (element[i] == x)
return ++i;
return 0;
}
template<class T> LinearList<T>& LinearList<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
throw OutOfBounds();
}
template<class T> LinearList<T>& LinearList<T>::Insert(int k, const T& x){
if (k < 0 || k > length)
throw OutOfBounds();
if (length == MaxSize)
throw NoMem();
for(int i = length - 1; i >= k; i--)
element[i + 1] = element[i];
element[k] = x;
length++;
return *this;
}
template<class T> void LinearList<T>::Output(ostream &out) const{
for (int i = 0; i < length; i++)
out << element[i] << ' ';
}
template<class T> ostream& operator<<(ostream& out, const LinearList<T>& x){
x.Output(out);
return out;
}
#endif
//主程序文件main.cpp
#include <iostream>
#include "LinearList.h"
using namespace std;
int main(){
try{
LinearList<int> L(5);
cout << "Length = " << L.Length() << endl;
cout << "IsEmpty = " << L.IsEempty() << endl;
L.Insert(0, 2).Insert(1, 6);
cout << "List is " << L << endl;
cout << "IsEmpty = " << L.IsEempty() << endl;
int z;
L.Find(1,z);
cout << "Fist element is " << z << endl;
cout << "Length = " << L.Length() << endl;
L.Delete(1, z);
cout << "Deleted element is " << z << endl;
cout << "List is " << L << endl;
}
catch(...){
cerr << "An exception has occurred" << endl;
}
}
运行效果