顺序表实现集合及大整数运算

来源:互联网 发布:linux设置时间 编辑:程序博客网 时间:2024/06/05 18:30
#include<iostream>
using namespace std;
const int MaxSize=5;
template<class DataType>
class Seqlist
{
public:
    Seqlist(){length=0;}
    Seqlist(DataType a[],int n);
    ~Seqlist(){}
    int Length(){return length;}
    DataType Get(int i);
    int Locate(DataType x);
    void Insert(int i,DataType x);
    DataType Delete(int i);
    void PrintList();


private:
    DataType data[MaxSize];
    int length;


};
template<class DataType>//顺序表一开始已经确定了顺序表的最大存储容量,所以要判断是否会上溢
Seqlist<DataType>::Seqlist(DataType a[],int n)
{
    if(n>MaxSize)
        cout<<"参数非法"<<endl;
    else
    {
         for(int i=0;i<n;i++)
         {
             data[i]=a[i];


         }
         length=n;//length=n写在循环外面
    }


}
template<class DataType>
DataType Seqlist<DataType>::Get(int i)//查找位置会涉及位置非法的问题
{
    if(i<1||i>length)
    {
        cout<<"查找位置非法";
    }
    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(i<1||i>length+1)cout<<"插入位置非法"<<endl;
    if(length>=MaxSize)cout<<"上溢"<<endl;
    for(int j=length;j>=i-1;j--)
    {
        data[j+1]=data[j];
    }
    data[i-1]=x;
    length++;//不要忘了还有长度这个变量
}
template<class DataType>
DataType Seqlist<DataType>::Delete(int i)//插入和删除都不要忘了改Length
{
    if(i<1||i>length)
        cout<<"位置非法"<<endl;
    if(length==0)


            cout<<"下溢"<<endl;
        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 a[5]={1,2,3,4,5};
    Seqlist<int> s(a,5);
    /*cout<<s.Get(5);
    cout<<endl;
    s.PrintList();
     cout<<endl;
    s.Delete(2);
    s.PrintList();
     cout<<endl;*/
     s.Insert(2,2);
    s.PrintList();
     cout<<endl;
     cout<<s.Locate(2);
}
0 0
原创粉丝点击