間接尋址

間接尋址是公式化描述和鏈表描述的組合。

大多數間接尋址鏈表操作的時間複雜性都與元素的總數無關。

在間接尋址方式中,使用一個指針表來跟蹤每個元素。可採用一個公式來定位每個指針的位置,以便找到所需要的元素。元素本身可能存儲在動態分配的節點或節點數組之中。

這裏寫圖片描述

間接尋址的類定義及其操作

#pragma once
template<class T>
class IndirectList 
{
public:
    IndirectList(int MaxListSize = 10);
    ~IndirectList();
    bool IsEmpty() const { 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; //一維T類型指針數組
    int length, 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;
};

template<class T>
bool IndirectList<T>::Find(int k, T& x) const
{
    //取第k個元素至x
    //如果不存在第k個元素,函數返回false,否則返回true
    if (k < 1 || k > length) return false; //不存在第k個元素
    x = *table[k - 1];
    return true;
};

template<class T>
IndirectList<T>& IndirectList<T>::Delete(int k, T& x)
{ 
    //把第k個元素傳送至x,然後刪除第k個元素
    // 如果不存在第k個元素,則引發異常OutOfBounds
    if (Find(k, x)) 
    {
        //向前移動指針k+l, ...
        for (int i = k; i < length; i++)
            table[i - l] = table[i];
        length--;
        return *this;
    }
    else throw OutOfBounds();
};

template<class T>
IndirectList<T>& IndirectList<T>::Insert(int k, const T& x)
{
    // 在第k個元素之後插入x
    // 如果不存在第k個元素,則引發異常OutOfBounds
    // 如果沒有足夠的空間,則傳遞NoMem異常
    if (k < 0 || k > length) throw OutOfBounds();
    if (length == MaxSize) throw NoMem();
    // 向後移動一個位置
    for (int i = length - 1; i >= k; i--)
        table[i + 1] = table[i];
    table[k] = new T;
    *table[k] = x;
    length++;
    return *this;
}

以上內容整理自網絡電子資料,僅供學習交流用,勿作商業用途。轉載請註明來源。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章