文章目录
顺序表的实现
- 建立顺序表类
将顺序表抽象数据类型用C++的类实现。其中成员变量实现顺序表存储结构,成员函数实现线性表的基本操作。由于线性表的数据元素类型不确定,所以采用C++的模板机制
const int maxSize = 100;//定义数组最大长度
template <class T>
class SeqList
{
public:
SeqList();//建立空的顺序表
SeqList(T a[], int n);//建立长度为n的顺序表
~SeqList();//析构函数
int length();//求线性表的长度
T Get(int i);//按位查找,查找第i个元素的值
int Locate(T x);//按值查找,查找值为x的元素
void Insert(int i, T x);//插入操作,在第i个位置插入值为x的元素
T Delete(int i);//删除操作,删除第i个元素
bool Empty();//判断线性表是否为空
void printList();//遍历操作,按序号依次输出各元素
private:
T data[maxSize];
int size;
};
- 各个成员函数的实现
无参构造
template <class T>
SeqList<T>::SeqList()
{
this->size = 0;
}
有参构造
template <class T>
SeqList<T>::SeqList(T a[], int n)
{
if (n > maxSize)
{
throw "参数非法";
}
for (int i = 0; i < n; i++)//这里是n不是this->size
{
//将数组全部赋值给顺序表
this->data[i] = a[i];
}
this->size = n;
}
析构函数
//顺序表是静态存储分配 顺序表无需销毁
template <class T>
SeqList<T>::~SeqList()
{
}
求线性表的长度
template <class T>
int SeqList<T>::length()
{
return this->size;
}
按位查找,查找第i个元素的值
template <class T>
T SeqList<T>::Get(int i)
{
if (i < 1 || i > this->size)
{
throw "查找位置非法";
}
else
{
return this->data[i - 1];
}
}
按值查找 返回序号(不是下标)
template <class T>
int SeqList<T>::Locate(T x)
{
for (int i = 0; i < this->size; i++)
{
if (this->data[i] == x)
{
return i + 1;
}
}
return 0;
}
插入操作,在第i个位置插入值为x的元素
template <class T>
void SeqList<T>::Insert(int i, T x)
{
if (this->size == maxSize)
{
throw "上溢";
}
if (i < 1 || i > size + 1)
{
throw "插入位置错误";
}
//后移操作
for (int j = this->size; j >= i; j--)
{
this->data[j] = this->data[j - 1];
}
this->data[i - 1] = x;
//不能忘了size++
this->size++;
}
删除操作,删除第i个元素
template<class T>
T SeqList<T>::Delete(int i)
{
T x;
if (this->size == 0)
{
throw "下溢";
}
if (i < 1 || i > this->size)
{
throw "删除位置错误";
}
x = this->data[i - 1];//取出位置i的元素
for (int j = i - 1; j < this->size -1; j++)
{
this->data[j] = this->data[j + 1];
}
this->size--;//不能忘了this->size--
return x;
}
判断线性表是否为空
template <class T>
bool SeqList<T>::Empty()
{
if (this->size == 0)
{
return true;
}
else
{
return false;
}
}
遍历操作,按序号依次输出各元素
template <class T>
void SeqList<T>::printList()
{
for (int i = 0; i < this->size; i++)
{
cout << this->data[i] << "\t";
}
cout << endl;
}
- 主函数实现
#include <iostream>
#include "SeqList.h"
#include <string>
using namespace std;
int main()
{
int r[5] = { 1,2,3,4,5 }, i, x;
SeqList<int> L{ r,5 };
cout << "当线性表的数据为:";
L.printList();//1 2 3 4 5
try
{
L.Insert(-2, 8);
cout << "执行插入操作后的数据为:";
L.printList();//1 8 2 3 4 5
}
catch (const char* str)
{
cout << str << endl;
}
cout << "当前线性表的长度为:" << L.length() << endl;//6
cout << "请输入查找的元素值:";
cin >> x;
i = L.Locate(x);//3
if (i == 0)
{
cout << "查找失败" << endl;
}
else
{
cout << "元素" << x << "的位置为:" << i << endl;//4
}
try
{
cout << "请输入查找第几个元素值:";
cin >> i;//1
cout << "第" << i << "个元素值是:" << L.Get(i) << endl;
}
catch (const char* str)
{
cout << str << endl;
}
try
{
cout << "请输入要删除第几个元素";
cin >> i;
x = L.Delete(i);
cout << "删除的元素是:" << x << ",删除后的数据为:";//8 2 3 4 5
L.printList();
}
catch (const char* str)
{
cout << str << endl;
}
return 0;
}
- 案例测试