测试函数:
//最基本的数据结构之一是线性表
/*
如下特点:
1. 顺序表的内存空间是一连串的地址空间
2. 与数据需要一个唯一的数组名一样,顺序表也需要有一个唯一的数组名来表示
3. 数据在顺序表中按先后顺序排列,存取是可根据位置随机存取
*/
#include <iostream>
#include "Seqlist.cpp"
using namespace std;
int main()
{
SeqList<int> mylist;
mylist.insertElement(0,0);
mylist.insertElement(1,0);
mylist.insertElement(2,0);
mylist.insertElement(3,0);
mylist.insertElement(4,0);
mylist.insertElement(5,5);
mylist.insertElement(88,1);
mylist.insertElement(99,9);
mylist.insertElement(8888,-1);
cout <<"length: "<< mylist.getlen() << endl;
for(int i = 0; i<mylist.getlen(); ++i)
{
cout << mylist.getElement(i) << " ";
}
cout << endl;
mylist.deleteElement(0);
mylist.deleteElement(mylist.getlen()-1);
mylist.deleteElement(3);
mylist.changeElement(mylist.getlen()-1, 100);
for(int i = 0; i<mylist.getlen(); ++i)
{
cout << mylist.getElement(i) << " ";
}
return 0;
}
Seqlist.h
#ifndef SEQLIST_H
#define SEQLIST_H
#include <iostream>
const int defaultSize = 10;
template <typename DataType>
class SeqList
{
public:
SeqList(int size = defaultSize);
~SeqList();
bool insertElement(DataType data, int location); //插
bool deleteElement(int location); //删除元素
DataType getElement(int location); //返回指定位置的元素
bool changeElement(int location, DataType newData); //修改指定位置的元素
int getlen() const;
private:
DataType *elements;
int maxSize; //顺序表的最大大小
int length; //顺序表的有效长度
};
#endif
Seqlist.cpp
#include "Seqlist.h"
template <typename DataType>
SeqList<DataType>::SeqList(int size)
{
if(size > 0)
{
maxSize = size;
elements = new DataType[maxSize];
length = 0;
}
}
template <typename DataType>
SeqList<DataType>::~SeqList()
{
delete[] elements;
}
template <typename DataType>
bool SeqList<DataType>::insertElement(DataType data, int location)
{
if(length >= maxSize || location < 0)
{
return false;
}
else
{
if(location <= length)
{
for(int i = length; i > location ; --i)
{
elements[i] = elements[i-1];
}
elements[location] = data;
++length;
return true;
}
else
{
return false;
}
}
}
template <typename DataType>
bool SeqList<DataType>::deleteElement(int location)
{
if((location) > (length - 1) || location < 0)
{
return false;
}
else
{
for(int i = location; i<(length-1); ++i)
{
elements[i] = elements[i+1];
}
--length;
return true;
}
}
template <typename DataType>
DataType SeqList<DataType>:: getElement(int location)
{
if(location > (length-1) || location < 0)
{
std::cout << " err argument" << std::endl;
return 0;
}
else
{
return elements[location];
}
}
template <typename DataType>
bool SeqList<DataType>::changeElement(int location, DataType newData)
{
if(location < 0 || length == 0 || location > (length-1))
{
return false;
}
else
{
elements[location] = newData;
return true;
}
}
template <typename DataType>
int SeqList<DataType>::getlen() const
{
return length;
}