1. 设计数据结构接口
LinearList{
实例:
0或多个元素的有序集合
操作:
Creat();
Destroy();
IsEmpty();
Length();
Find(k,x);
Search(x);
Delete(k,x);
Insert(k,x);
Output(out);
}
2. 设计类的基本描述
#ifndef LinearList_
#define LinearList_
#include <iostream>
#include <stdlib.h>
#include "xcept.h"
using namespace std;
template<class T>
class LinearList{
public:
LinearList(int MaxListSize=10);
~LinearList(){delete[] element;}
bool IsEmpty() const {return length==0;}
int Length()const {return length;}
bool Find(int k,T &x) const;
int Search(const T &x) const;
LinearList<T>& Delete(int k,T& x)
LinearList<T>& Insert(int k,const T& x);
void Output() const;
private:
int length;
int MaxSize;
T *elemment;
};
#endif
#include<new.h>
class NoMem {
public:
NoMem() {}
};
void my_new_handler(){
throw NoMem();
}
new handler Old_Handler = set_new_handly(my_new_handler);
class OutOfBounds {
public:
OutOfBounds() {}
};
操作的实现
tempalte<class T>
LinearList<T>::LinearList(int MaxListSize){
MaxSize = MaxListSize;
element=new T[MaxSize];
length=0;
}
template<class T>
bool LinearList<T>::Find(intk,T& x)const{
if(K<1||k>length)
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 OutBounds();
}
template<class T>
LinearList<T>& LinearList<T>::Insert(int k,const T& x){
if(k<0||k>length) throw OutBounds();
if(length==MaxSize) throw NoMem();
for(int i=length-i;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;
}
void main(void)
{
try {
LinearList<int> L(5);
cout << "Length = " << L.Length() << endl;
cout << "IsEmpty = " << L.IsEmpty() << endl;
L.Insert(0,2).Insert(1,6);
cout << "List is " << L << endl;
cout << "IsEmpty = " << L.IsEmpty() << endl;
int z;
L.Find(1,z);
cout << "First 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;
}
}