数据结构学习笔记1顺序表

顺序表

顺序表的定义思路

初始化需要定义的三个要素

  • head——未初始化的动态数组
  • length——记录顺序表的长度
  • size——记录顺序表分配的存储容量

C语言代码实现

typedef struct Table
{
    int * head;
    int length;
    int size;
}table;

顺序表的初始化思路

  • 给head动态数据申请足够大小的物理空间
  • 判断是否申请成功
  • 给size和length赋初值

C语言代码实现

table initTable()
{
    table t;
    t.head=(int*)malloc(Size*sizeof(int));
    if (!t.head)
    {
        printf("Initialization failure");
        exit(0);
    }
    t.length = 0;
    t.size =Size;
    return t;
}

顺序表插入操作

  • 判断插入本身是否存在问题,如插入元素位置
  • 看顺序表是否有多余的存储空间提供给插入的元素,如果没有,需要申请
  • 将从插入位置开始的后续元素,逐个后移
  • 将苏旭插入元素,添加到顺序表的相应位置
  • 长度+1

C语言代码实现

table addTable(table t, int elem, int add)
{
    if (add>t.length+1||add<1)
    {
        printf("There is a problem with the insertion position");
        return t;
    }

    if (t.length = t.size)
    {
        t.head=(int *)realloc(t.head, (t.size+1)*sizeof(int));
        if (!t.head)
        {
            printf("Memory allocation failed");
            return t;
        }
        t.size+=1;
    }
    for (int i = t.length; i < add-1; i--)
    {
        t.head[i+1]=t.head[i];
    }
    
    t.head[add-1] = elem;
    t.length++;
    return t;
}

顺序表删除元素

  • 后续元素整体前移

C语言代码实现

table delTable(table t, int del){
    if (del>t.length || del<1)
    {
        printf("There is an error in the location of the deleted element!");
        exit(0);
    }
    for (int i = del; i < t.length; i++)
    {
        t.head[i-1] = t.head[i];
    }
    t.length--;
    return t;
}

顺序表查找元素

顺序查找算法
C语言实现代码

int searchTable(table t, int elem){
    for (int i = 0; i < t.length; i++)
    {
        if (t.head[i]==elem)
        {
            return i+1;
        }
        
    }
    return -1;
}

顺序表更改元素

  • 找到目标元素
  • 直接修改该元素的值

C语言代码实现

table changeTable(table t, int elem, int newElem){
    int change = searchTable(t, elem);
    t.head[change-1] = newElem;
    return t;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadowCui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值