指针数组的应用-间接寻址表

采用间接寻址可以非常快速地访问元素,用一个指针来跟踪每个元素,元素可能位于动态分配的节点或数组之中。

首先定义好该数据结构的功能:

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;
}

结果为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值