采用间接寻址可以非常快速地访问元素,用一个指针来跟踪每个元素,元素可能位于动态分配的节点或数组之中。
首先定义好该数据结构的功能:
template<class T>
class IndirectList {
public:
IndirectList(int MaxListSize = 10);
~IndirectList();
bool IsEmpty() { return length == 0; }
int Length()const { return length; }
bool Find(int k, T& x)const;
int Search(const T& x)const;
IndirectList<T>& Delete(int k, T& x);
IndirectList<T>& Insert(int k, const T& x);
void Output(ostream& out)const;
private:
T **table;
int ength,MaxSize;
};
编写构造函数和析构函数:
template<class T>
IndirectList<T>::IndirectList(int MaxListSize)
{
MaxSize = MaxListSize;
table = new T*[MaxSize];
length = 0;
}
template<class T>
IndirectList<T>::~IndirectList()
{
for (int i = 0; i < length; i++)
delete table[i];
delete table;//同时要删除指向指针数组中指针的指针
}
Find( )函数,与链表中Find函数功能类似。
template<class T>
bool IndirectList<T>::Find(int k, T& x)
{
if (k<1 || k> length)return false;
x = *table[k - 1];
return true;
}
Delete()函数:
template<class T>
IndirectList<T>& IndirectList<T>::Delete(int k,T& x) {
if (Find(k, x)) {
for (int i = k; i < length; i++)
table[i - 1] = table[i];
length--;
return *this;
}
else throw OutOfBounds();
}
和线性表的Delete()函数很相似。
类似地,Insert()函数:
template<class T>
IndirectList<T>& IndirectList<T>::Insert(int k, const T& x)
{
if (k<0 || k>length)throw OutOfBounds();
if (length == MaxSize)throw NoMem();
for (int i = length - i; i >= k; i--)
table[i + 1] = table[i];
table[k] = new T;
*table[k] = x;
length++;
return *this;
}
将以上程序保存在头文件IndirectList.h中。
问题:编写IndirectList类的成员函数Search(),测试其正确性,并指出函数的时间复杂性。
解答:
template<class T>
int IndirectList<T>::Search(const T& x)const
{
int i = 0;
while (i < length)
{
if (*table[i] == x)
{
return i;
break;
}
else
i++;
}
return 0;
}
测试:
#include "stdafx.h"
#include<iostream>
#include "xcept.h"
#include "IndirectList.h"
using namespace std;
int main()
{
IndirectList<int> L(10);
L.Insert(0, 3).Insert(1, 6).Insert(2, 9).Insert(3, 12);
cout << "间接寻址表为: " << endl;
cout << L;
cout << endl;
cout << "Search()函数测试:" << endl;
cout << "元素 9的索引是: "<<L.Search(9) << endl;
cout << "元素12的索引是: " << L.Search(12) << endl;
return 0;
}
结果为: