作业0828

 使用C++手动封装一个顺序表,包含成员数组一个,成员变量N个

#include <iostream>
#include <string>

using namespace std;

using datatype = int;

struct Seqlist
{
private:
    datatype *data = NULL;
    int size = 0;
    int len = 0;

public:
    //初始化函数
    void init(int s);
    //判空函数
    bool empty();
    //判满函数
    bool full();
    //添加数据函数
    bool add(datatype e);
    //求当前顺序表的实际长度
    int length();
    //求顺序表的大小
    int SIZE();
    //任意位置插入函数
    bool insert_pos(int pos, datatype e);
    //任意位置函数函数
    bool delete_pos(int pos);
    //访问容器中任意一个元素 at
    datatype &at(int index);
    //二倍扩容
    void expend();
};

//初始化函数
void Seqlist::init(int s)
{
    size = s;
    data = new datatype[size];
}

//判空函数
bool Seqlist::empty()
{
    return 0 == len;
}

//判满函数
bool Seqlist::full()
{
    return size == len;
}

//添加数据函数
bool Seqlist::add(datatype e)
{
    if(NULL == data)
    {
        cout << "添加失败" << endl;
        return false;
    }

    if(full())
    {
        expend();
    }

    data[len] = e;
    len++;

    cout << "添加成功" << endl;
    return true;
}

//求当前顺序表的实际长度
int Seqlist::length()
{
    return len;
}

//求顺序表的大小
int Seqlist::SIZE()
{
    return size;
}

//任意位置插入函数
bool Seqlist::insert_pos(int pos, datatype e)
{
    if(NULL == data)
    {
        cout << "插入失败" << endl;
        return false;
    }

    if(full())
    {
        expend();
    }

    for(int i=len; i>pos; i--)
    {
        at(i) = at(i-1);
    }

    at(pos) = e;
    len++;

    cout << "插入成功" << endl;
    return true;
}

//任意位置删除函数
bool Seqlist::delete_pos(int pos)
{
    if(empty() || NULL == data)
    {
        cout << "删除失败" << endl;
        return false;
    }

    for(int i=pos; i<len; i++)
    {
        at(i) = at(i+1);
    }
    len--;

    cout << "删除成功" << endl;
    return true;
}

//访问容器中任意一个元素 at
datatype &Seqlist::at(int index)
{
    return data[index];
}

//二倍扩容
void Seqlist::expend()
{
    size = size*2;
    datatype *temp = new datatype[size];
    memcpy(temp, data, size/2*sizeof(datatype));
    delete []data;
    data = temp;
}

int main()
{
    Seqlist L;
    L.init(10);
    for(int i=0; i<30; i++)
    {
        L.add(i);
        cout << "此时顺序表大小为:" << L.SIZE() << endl;
        cout << "此时顺序表实际长度为:" << L.length() << endl;
    }

    L.insert_pos(1, 666);
    L.delete_pos(1);

    for(int i=0; i<L.length(); i++)
    {
        cout << L.at(i) << " ";
    }
    cout << endl;

    return 0;
}

 思维导图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值