// 顺序列表的模板类实现
#include <iostream>
using namespace std;
template <class elemType>
class seqList
{
private:
elemType* data;
int length;
int maxSize;
void doubleSpace();
public:
seqList(int initSize = 10);
~seqList() { delete[] data; }
void insert(elemType number);
void remove(int i);
void traverse();
elemType visit(int i);
int getLen();
};
template <class elemType>
seqList<elemType>::seqList(int initSize){
data = new int[initSize];
maxSize = initSize;
length = 0;
}
template <class elemType>
void seqList<elemType>::doubleSpace() {
elemType *tmp = data;
data = new elemType[2 * length];
for (int i = 0; i < length; i++) data[i] = tmp[i];
maxSize = 2 * length;
delete [] tmp;
}
template <class elemType>
void seqList<elemType>::insert(elemType number){
if (length == maxSize) doubleSpace();
data[length] = number;
length++;
}
template <class elemType>
void seqList<elemType>::remove(int i){
if (i < 0 || i >= length) {
cout << "Illegal index" << endl;
return;
}
for (int j = i; j < length-1; j++) {
data[j] = data[j + 1];
}
length--;
}
template <class elemType>
void seqList<elemType>::traverse() {
for (int i = 0; i < length; i++) {
cout << data[i] << endl;
}
}
template <class elemType>
elemType seqList<elemType>::visit(int i) {
return data[i];
}
template <class elemType>
int seqList<elemType>::getLen() {
return this->length;
}
int main()
{
seqList<int> tmp(3);
tmp.insert(1);
tmp.insert(2);
tmp.insert(3);
tmp.insert(4);
tmp.traverse();
cout<<tmp.getLen()<<endl;
return 0;
}
C++顺序列表的实现(采用模板类)
最新推荐文章于 2024-06-22 15:51:58 发布