数据结构学习笔记1顺序表
程序员文章站
2022-07-14 19:49:55
...
顺序表
顺序表的定义思路
初始化需要定义的三个要素
- 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;
}
联系我
个人博客:http://www.awsg.online
博客园:https://www.cnblogs.com/AWSG-Shaodw/
CSDN:https://blog.csdn.net/AngleWithShotgun/
简书:https://www.jianshu.com/u/df7323cbc116
微信公众号: