C++线性表

//SeqList.h

#define MaxSize 100

template <class DataType>
class SeqList
{
    private:
        DataType data[MaxSize];     //存放数据元素的数组
        int length;     //线性表的长度

    public:
        SeqList(){length=0;}        //构建一个空顺序表
        SeqList(DataType a[],int n);        //构造一个长度为n的顺序表
        ~SeqList(){}       //析构函数
        int Length(){return length;}        //求线性表长度
        DataType Get(int i);        //取线性表中第i个元素
        int Locate(DataType x);     //取线性表中值为x的元素的序号
        void Insert(DataType x,int i);      //插入操作,在i插入x
        DataType Delete(int i);     //删除操作,删除第i个元素
        void PrintList();       //遍历操作,输出个元素
};

//构造一个长度为n的顺序表
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>
DataType SeqList<DataType>::Delete(int i)
{
    DataType x; 
    if (length==0) throw "下溢";
    if (i<1&&i>length) throw "位置非法";
    x=data[i-1];
    for (;i<length;i++)
    {
        data[i-1]=data[i];
    }
    length--;
    return x;
}

//插入
template <class DataType>
void SeqList<DataType>::Insert(DataType x,int i)
{
    if (i>MaxSize) throw "上溢";
    if (i<1&&i>length) throw "位置非法";
    for (int j=length;j>=i;j--)
    {
        data[j]=data[j-1];
        data[j-1]=x;
    }
    length++;
}

//遍历
template <class DataType>
void SeqList<DataType>::PrintList()
{
    cout<<"当前线性表为:"<<endl;
    for (int i=0;i<length;i++)
    {
        cout<<data[i]<<'\t';
    }
    cout<<endl;
}
//main.cpp
#include <iostream>
#include "SeqList.h"

using namespace std;

void main()
{
    int a[10]={2,5,4,8,9,1,3,7,6,0};        //测试数组
    //顺序表
    cout<<"初始化线性表"<<endl;
    SeqList<int> sl(a,10);

    sl.PrintList();
    cout<<sl.Length()<<endl;

    cout<<"获取i位元素"<<endl;
    cout<<sl.Get(3)<<endl;

    cout<<"i位插入元素x"<<endl;
    sl.Insert(10,5);
    sl.PrintList();
    cout<<sl.Length()<<endl;

    cout<<"值为x的元素"<<endl;
    cout<<sl.Locate(6)<<endl;

    cout<<"删除i位元素"<<endl;
    cout<<sl.Delete(8)<<endl;
    sl.PrintList();
    sl.Length();
}
posted @ 2016-03-23 10:49  伤心中国人  阅读(228)  评论(0编辑  收藏  举报