SeqList.h
#pragma once
#include <iostream>
using namespace std;
const int MaxSize = 100;
template <class DataType>
class SeqList
{
public:SeqList();//建立空的顺序表 SeqList(DataType a[], int n);//建立长度为n的顺序表~SeqList();//析构函数int Length();//求线性表的长度DataType Get(int i);//按位查找,查找第i位元素的值int Locate(DataType x);//按值查找,查找值为x的元素序号void Insert(int i, DataType x);//插入操作,在第i个位置插入值为x的元素DataType Delete(int i);//删除操作,删除第i个位置的元素int Empty();//判断顺序表是否为空void PrintList();//遍历操作,按序号依次输出各元素
private:DataType data[MaxSize];//存放元素的数组 int length;//顺序表的长度
};template<class DataType>
SeqList<DataType>::SeqList()//建立空的顺序表
{length = 0;
}template<class DataType>
SeqList<DataType>::SeqList(DataType a[], int n)//建立长度为n的顺序表
{if (n > MaxSize)throw("参数违法");for (int i = 0; i < n; i++)data[i] = a[i];length = n;
}
template<class DataType>
SeqList<DataType>::~SeqList() {//析构函数
}
template<class DataType>
int SeqList<DataType>::Empty() // 判断顺序表是否为空
{if (length)return true;elsereturn false;}template<class DataType>
int SeqList<DataType>::Length()//求线性表的长度
{return length;
}
template <class DataType>
void SeqList<DataType>::PrintList()
{for (int i = 0; i < length; i++)cout << data[i] << '\t';//依次输出线性表的元素值cout << endl;
}
template <class DataType>
DataType SeqList<DataType>::Get(int i)//按位查找,查找第i位元素的值
{if (i<1 || i>length)throw "查找位置非法";elsereturn data[i - 1];
}
template <class DataType>int SeqList<DataType>::Locate(DataType x)//按值查找,查找值为x的元素序号
{for (int i = 0; i < length; i++)if (data[i] == x) return i + 1;//返回其序号i+1return 0;//推出循环,说明查找失败
}template <class DataType>
void SeqList<DataType>::Insert(int i, DataType x)//插入操作,在第i个位置插入值为x的元素
{if (length == MaxSize)throw"上溢出";if (i<1 || i>length + 1)throw"插入位置错误";for (int j = length; j >= i; j--)data[j] = data[j - 1];data[i - 1] = x;length++;}
template <class DataType>
DataType SeqList<DataType>::Delete(int i)//删除操作,删除第i个位置的元素
{DataType x;if (length == 0)throw"下溢";if (i<1 || i>length)throw"删除位置错误";x = data[i - 1];//取出i位置的元素for (int j = i; j < length; j++)data[j - 1] = data[j];//此处j 已经是元素所在的数组下标length--;return x;
}
main.cpp
#include <iostream>
#include "SeqList.h"
using namespace std;
int main()
{int r[5] = {1,2,3,4,5},i,x;SeqList<int>L( r,5 );//建立具有5个元素的顺序表cout << "当前顺序表的数据为:";L.PrintList();try{L.Insert(2, 8);cout << "输出插入后的数据为:";L.PrintList();}catch (char* str) { cout << str << endl; }cout << "当前线性表的长度为:" << L.Length() << endl;cout << "请输入要查找的元素值:" << endl;cin >> x;i = L.Locate(x);if (0 == i)cout << "查找失败" << endl;elsecout << "元素" << x << "的位置为:" << i << endl;try{cout << "请输入查找第几个元素值:";cin >> i;cout << "第" << i << "个元素值是" << L.Get(i) << endl;}catch (char* str) { cout << str << endl; }try{cout << "请输入要删除第几个元素:";cin >> i;x = L.Delete(i);cout << "删除的元素是:" << x << ",删除后数据为:";L.PrintList();}catch (char* str) { cout << str << endl; }return 0;
}