您的位置:首页 > 理论基础 > 数据结构算法

数据结构之线性表顺序存储实现-顺序表(C++)

2019-08-03 11:56 260 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/xiaohuojian123/article/details/98319491

#include <iostream>
using namespace std;

//核心代码
const int MaxSize = 100;
template <class DataType>
class SeqList
{
private:
    DataType data[MaxSize];       //存放数据元素的数组,注意:线性表的第1个元素存放在数组下标为0的位置,以此类推
    int length;                                //线性表的长度

public:
    SeqList(){length=0;}               //无参构造函数,建立长度为0的顺序表
    SeqList(DataType a[],int n);   //有参构造函数,建立长度为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();                     //遍历
};

//有参构造函数
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 "查找位置非法";
    return data[i-1];
}

//按值查找
template <class DataType>
int SeqList<DataType>::Locate(DataType x)
{
    for(int i=0;i<length;i++){
        if(x==data[i])
            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 k=length;k>i-1;k--){
        data[k]=data[k-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 k=i-1;k<length-1;k++){
        data[k]=data[k+1];
    }
    length--;
    return x;
}

//遍历
template <class DataType>
void SeqList<DataType>::PrintList()
{
    for(int i=0;i<length;i++)
        cout<<data[i]<<" ";
}


int main()
{
    SeqList<int> p;
    p.Insert(1,1);
    p.Insert(2,2);
    p.PrintList();
    p.Insert(2,3);
    cout<<p.Length()<<endl;
    p.PrintList();
    cout<<p.Get(3)<<endl;
    p.Insert(4,4);
    p.PrintList();
    p.Delete(1);
    p.PrintList();
    cout<<p.Locate(4)<<endl;
    p.Delete(2);
    p.PrintList();
    return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: