C++实现线性表的顺序存储结构

时间:2023-03-10 03:14:56
C++实现线性表的顺序存储结构

将线性表的抽象数据类型定义在顺序表存储结构下用C++的类实现,由于线性表的数据元素类型不确定,所以采用模板机制。

 头文件seqlist.h
#pragma once
#include <iostream>
const int MaxSize = ;
template<class T>// 定义模板类
class SeqList
{
public: SeqList() { Length = ; }; // 无参构造函数,建立一个空的顺序表
SeqList(T a[], int n); // 有参构造函数,建立一个长度为n的顺序表
~SeqList() {}; // 空的析构函数
int leng() { return Length; } // 求线性表的长度
T get(int i); // 按位查找第i个元素
int locate(T x); // 按值查找值为x的元素序号
void insert(int i, T x); // 在第i个位置插入值为x的元素
T Delete(int i); // 删除第i个元素
void printlist(); // 打印线性表 private:
T data[MaxSize];
int Length; }; #pragma region 成员函数定义 template<class T>
inline SeqList<T>::SeqList(T a[], int n)
{
if (n > MaxSize)throw"参数非法";
for (int i = ; i < n; i++)
data[i] = a[i];
Length = n;
} template<class T>
T SeqList<T>::get(int i)
{
if (i< || i>Length)throw"查找位置非法";
else return data[i - ];
} template<class T>
int SeqList<T>::locate(T x)
{
for (int i = ; i < Length; i++)
{
if (data[i] == x)
return i + ;
}
return ;
} template<class T>
void SeqList<T>::insert(int i, T x)
{
if (Length >= MaxSize)throw "上溢";
if (i< || i>Length + )throw "插入位置非法"; for (int j = Length; j >= i; j--)
data[j] = data[j - ];
data[i-] = x;
Length++;
} template<class T>
T SeqList<T>::Delete(int i)
{
if (Length == )throw"下溢";
if (i< || i>Length)throw"位置非法";
T x = data[i - ];
for (int j = i; j < Length; j++)
data[j - ] = data[j];
Length--;
return x;
} template<class T>
void SeqList<T>::printlist()
{
for (int i = ; i < Length; i++)
cout << data[i] << endl; }
主函数
#include "seqlist.h"
using namespace std;
int main()
{
int arry[] = { , , , , , , , , , };
// 三种创建类对象的方法
SeqList<int> seqlist;
SeqList<int> seqlist1(arry,);
SeqList<int>* seqlist2 = new SeqList<int>(arry, );
cout << seqlist1.get() << endl;
cout << seqlist2->get() << endl;
cout << seqlist1.locate() <<endl;
cout << seqlist2->locate() << endl;
seqlist1.insert(, );
seqlist2->insert(, );
seqlist1.Delete();
seqlist2->Delete();
seqlist1.printlist();
seqlist2->printlist(); system("pause");
return ;
}