整数顺序表的基本运算

#include<bits/stdc++.h>
using namespace std;
const int MaxSize = 100;
template<class DataType>
class SeqList
{
public:
    SeqList(){length=0;}
    SeqList(DataType a[],int n);
    ~SeqList() {};
    int Length(){return length;}//求线性表的长度
    DataType Get(int i);//按位查找,在线性表中查找第i个元素
    int Locate(DataType x);//按值查找,在线性表中查找值为x的元素符号
    void Insert(int i,DataType x);//插入操作,在线性表中第i个位置插入值为x的元素
    DataType Delete(int i);//删除操作,删除线性表的第i个元素
    void PrintList();//遍历操作,按序号依次输出各元素
private:
    DataType data[MaxSize];
    int  length;
};
//顺序表有参构造函数
template<class DataType>
SeqList<DataType>::SeqList(DataType a[], int n)
{
    if(n>MaxSize)throw "参数非法";
    for(int i=0;i<n;i++)
        data[i]=a[i];
    length=n;
}
//按位查找
template<class DataType>
DataType SeqList<DataType>::Get(int i)
{
    if(i<1 && i>length) throw"查找位置非法";
    else return data[i-1];
}
//顺序表按值查找位置算法
template<class DataType>
int SeqList<DataType>::Locate(DataType x)
{
    for(int i=0;i<length;i++)
         if(data[i]==x)
         return i+1;
    return  0;
}
//顺序表插入算法
template<class DataType>
void  SeqList<DataType>::Insert(int i, DataType 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)
{
    if(length==0)throw"下溢";
    if(i<1||i>length)throw"位置";
    DataType x=data[i-1];
    for(int j=i;j<length;j++)
    data[j-1]=data[j];
    length--;
    return x;
}
//顺序表遍历算法
template<class DataType>
void  SeqList<DataType>::PrintList()
{
    for(int i=0;i<length;i++)
    cout<<data[i]<<" ";
}
int main()
{
    int s,a[MaxSize];
    cin>>s;
    for(int i=0;i<s;i++)
    cin>>a[i];
    SeqList<int>b(a,s);
    b.PrintList();
    cout<<endl;
    try
    {
        b.Delete(1);
    }catch (char *s){cout<<s<<endl;}
    b.PrintList();
    cout<<endl;
    cout<<b.Length()<<endl;
    try
    {
        b.Insert(2,100);
    }catch(char *s){cout<<s<<endl;}
    b.PrintList();
    cout<<endl;
    cout<<b.Locate(100)<<endl;
    cout<<b.Get(5)<<endl;
    system("pause");
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值