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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章