使用模版类来实现线性表的顺序储存将会变的非常简单,我们不必像使用C语言一样,将数据和算法分离时使用非常繁琐的类型转换了,而我们直接使用模版中的typename就可以解决这个问题。具体实现的代码如下,都有详细的标注和测试代码:
#pragma once template<typename T> class SeqList { public: SeqList(int capacity); ~SeqList(); int insert(int pos, T& data); // 在某位置插入数据 T remove(int pos); // 删除某位置数据 void clear(); // 清空线性表 T get(int pos); // 获取某位置数据 int length(); // 获取线性表有效元素个数 int capacity(); // 获取线性表总长度 private: // 容量 int m_capacity; // 已有数据长度 int m_length; // 指针变量,用来动态分配数组 T* m_array; }; template<typename T> int SeqList<T>::capacity() { // 返回总长度 return m_capacity; } template<typename T> int SeqList<T>::length() { // 返回有效节点个数 return m_length; } template<typename T> T SeqList<T>::get(int pos) { // 返回 pos 位置的数据 return m_array[pos]; } template<typename T> void SeqList<T>::clear() { // 把有效节点个数置为0 m_length = 0; } template<typename T> T SeqList<T>::remove(int pos) { // 记录被删除的元素内容 T tmp = m_array[pos]; // 循环把被删除位置后面的数据依次向前移动一个 for (int i = pos + 1; i < m_length; i++) { m_array[i - 1] = m_array[i]; } // 线性表长度-- m_length--; // 返回被删除的数据 return tmp; } template<typename T> int SeqList<T>::insert(int pos, T& data) { // 循环将要插入数据位置后面的数据一次向后移动一次 for (int i = m_length; i > pos; i--) { m_array[i] = m_array[i - 1]; } // 在空出的pos位置插入数据 m_array[pos] = data; // 有效长度++ m_length++; return 0; } template<typename T> SeqList<T>::~SeqList() { // 销毁线性表数组 delete[] m_array; } template<typename T> SeqList<T>::SeqList(int capacity) { // 根据capacity长度申请一块空间存放数据 m_array = new T[capacity]; // 初始化两个成员变量 m_capacity = capacity; m_length = 0; }
测试代码:
#include <iostream> #include "seqlist.hpp" using namespace std; int main(int argc, char* argv[]) { SeqList<int> list(10); for (int i = 0; i < 10; i++) { list.insert(0, i); } for (int j = 0; j < list.length(); j++) { cout << list.get(j) << " "; } cout << endl << "delete index 5 value is : " << list.remove(5) << endl; for (int j = 0; j < list.length(); j++) { cout << list.get(j) << " "; } list.clear(); return 0; }
One Reply to “模版类实现线性表的顺序储存”