线性表主要有两中表现方式,一种是连续存储式,例如数组,另一种是非连续存储式,例如链表。 相比于链表,数组最大的好处就在于可以随机存取,链表的最大优势是,能够有效利用存储空间,合理的添加,删除操作只需要o(1)。于是诞生了间接寻址,即是把数组与链表的优点结合起来。
代码如下:
#ifndef INDIRECTLIST_HH
#define INDIRECTLIST_HH
#include <stdio.h>
template<typename T>
class CIndrectList{
private:
// pointe to a potiner which point to a T type object;
T** m_ppTable;
// length of CurrentIndrectList;
unsigned int m_nLength;
unsigned int m_nSize;
public:
// constructor;
CIndrectList(int size);
~CIndrectList();
// methods;
// Insert;
CIndrectList& mInsert(int k, const T& data);
// Delete;
CIndrectList& mDelete(int k, const T& data);
// find;
bool mFind(int k, const T& data) const;
// length;
int mLength() const;
// size;
int mSize() const;
}; // CIndrectList;
// implement;
// constructors;
template<typename T>
CIndrectList<T>::CIndrectList(int size = 10):
m_nLength(0),m_nSize(size){
m_ppTable = new T*[m_nSize];
}
template<typename T>
CIndrectList<T>::~CIndrectList(){
for(int i = 0; i < m_nLength; i ++)
delete m_ppTable[i];
delete [] m_ppTable;
}
// Insert data after (k-1)th element;
template<typename T>
CIndrectList<T>& CIndrectList<T>::mInsert(int k, const T& data){
if( k < 0 || k > m_nLength){
printf("Input wrong index in Insert\n;");
return *this;
}
if(m_nLength == m_nSize){
printf("Not enough Space\n");
return *this;
}
// move elements to contain k;
for(int i = m_nLength - 1; i >= k; i --){
m_ppTable[i + 1] = m_ppTable[i];
}
// add data;
m_ppTable[k] = new T;
*m_ppTable[k] = data;
m_nLength ++;
return *this;
}
// Delete;
template<typename T>
CIndrectList<T>& CIndrectList<T>::mDelete(int k, const T& data){
if(mFind(k,data)){
delete m_ppTable[k - 1];
for(int i = k; i < m_nLength; i ++)
m_ppTable[i - 1] = m_ppTable[i];
m_nLength --;
}
return *this;
}
template<typename T>
bool CIndrectList<T>::mFind(int k, const T& data) const{
if(k > m_nLength || k <= 0){
printf("Input wrong index in Find\n;");
return false;
}
return (*(m_ppTable[k - 1]) == data) ? true : false;
}
template<typename T>
int CIndrectList<T>::mLength() const{
return m_nLength;
}
template<typename T>
int CIndrectList<T>::mSize() const{
return m_nSize;
}
#endif
测试代码如下:
#include "IndrectList.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
CIndrectList<int> list(5);
list.mInsert(0,1);
cout << list.mLength() << endl;
list.mInsert(1,2);
cout << list.mLength() << endl;
list.mDelete(1,1);
list.mDelete(1,2);
list.mDelete(2,2);
cout << list.mLength() << endl;
system("pause");
return 0;
}
结果如下:
1
2
Input wrong index in Find
0
请按任意键继续. . .