寒假数据结构学习Day3

       线性表线性储存头插,头删,尾插,尾删,特定位置增删,代码的实现

检查数据表,扩容一般是扩俩倍。

void SeqListCheckCapacity(SL* ps)
{
    //如果没有空间或者空间不足,就扩容
    if (ps->size == ps->capacity)
    {
        int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
        SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
        if (tmp == NULL)  //判断开辟内存是否成功
        {
            printf("realloc fail\n");
            exit(-1);
        }
        ps->a = tmp;
        ps->capacity = newcapacity;
    }
}

尾插,尾删

void SeqListPushBack(SL* ps, SLDataType x)     //尾插
{
    //如果没有空间或者空间不足,就扩容
    if (ps->size == ps->capacity)
    {
        int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
        SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
        if (tmp == NULL)  //判断开辟内存是否成功
        {
            printf("realloc fail\n");
            exit(-1);
        }
        ps->a = tmp;
        ps->capacity = newcapacity;
    }
    ps->a[ps->size] = x;
    ps->size++;
}


void SeqListPopBack(SL* ps)     //尾删
{
    SeqListCheckCapacity(ps);
    assert(ps->size > 0);
    ps->size--;
}

头插,头删

插入数据后都要往后挪一项。

void SeqListPushFront(SL* ps, SLDataType x)      //头插
{
    SeqListCheckCapacity(ps);
    //挪动数据
    int end = ps->size  - 1;
    while (end >= 0)
    {
        ps->a[end + 1] = ps->a[end];
        --end;
    }
    ps->a[0] = x;
    ps->size++;
}

void SeqListPopFront(SL* ps)     //头删
{
    assert(ps->size > 0);
    int begin = 1;
    while (begin < ps->size)
    {
        ps->a[begin - 1] = ps->a[begin];
        ++begin;
    }
    ps->size--;
}

指定就位置插人删除数据

int SeqListFind(SL* ps, SLDataType x)   //找到返回x位置下标,没有找到返回-1
{
    int i = 0;
    while (i < ps->size)
    {
        if (x == ps->a[i])
        {
            return i;
        }
        i++;
    }
    return -1;
}


void SeqListInsert(SL* ps, int pos, SLDataType x)   //指定pos下标位置插入
{
    SeqListCheckCapacity(ps);
    int k = ps->size;
    for (; k >pos; k--)
    {
        ps->a[k] = ps->a[k-1];
    }
    ps->a[pos] = x;
    ps->size++;
}

线性储存与数组区别不大,在指定位置增删需要都要挪位置。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值