什么是顺序表?
顺序表是链表中的一种,顾名思义,使用线性表的顺序存储结构生成的表,叫做顺序表。表中的第一个元素称为首地址,通过首地址,可以访问到表中储存的所有数据,废话不多说,现在上代码。
用c语言创建一个顺序表
代码
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <stdlib.h>
#define Size 4
typedef struct Table{
int *head;
int length;
int size;
}table;
table initTable(){
table t;
t.head = (int*)malloc(Size * sizeof(int));//分配内存空间
t.length = 0;//定义数组长度
t.size = Size;//定义数组大小
return t;
}
顺序表建立好了,接下来就是写多几个函数对顺序表的操作,首先是添加一个元素
//首先定义一个添加进顺序表的函数
table addData(table t,int num,int data)
{
if (t.length+1 <num || num<1)
{
printf("您插入的位置有问题");//需要判断插入的位置
return t;
}
if (t.length == t.size ) {//如果空间不足,就需要申请空间
t.head = (int*)realloc(t.head,(t.size + 1) * sizeof(int));
if (!t.head){
printf("分配内存失败");
return t;
}
t.size += 1;
}
for (int i = t.length-1; i >= num-1; i--) {//这里循环递减把原来的元素挤到后面去
t.head[i + 1] = t.head[i];
}
t.head[num-1] = data;//后面插入数据
t.length++;//长度++
return t;
}
遍历所有元素,这里不过多做讲解
void showData(table t)
{
for (int i = 0; i < t.length; i++)
{
printf("%d", t.head[i]);
}
printf("\n");
}
删除一个元素
table delData(table t,int num)
{
if (t.length < num)
{
printf("找不到您删除的地址");
return t;
}
for (int i = num; i <t.length; i++)
{
t.head[i - 1] = t.head[i];
}
t.length--;
return t;
}
编辑一个元素
table updateData(table t, int num, int data)
{
if (t.length < num) {
printf("找不到您修改的地址");
return t;
}
t.head[num - 1] = data;
return t;
}
查找一个元素,返回它的位置
int selectData(table t, int data)
{
for (int i = 0; i < t.length; i++)
{
if (t.head[i] == data)
{
return i + 1;
}
}
return -1;
}
最终运行所写的函数
int main() {
for (int i = 0; i < t1.size; i++) {//这里我先填入4个值进入顺序表
t1.head[i] = i+1;
t1.length++;
}
showData(t1);
t1 = addData(t1, 4, 5);
showData(t1);
t1 = delData(t1, 4);
showData(t1);
t1 = updateData(t1, 4, 6);
showData(t1);
int place;
place = selectData(t1, 6);
printf("%d", place);
system("pause");
}
运行结果

结语
顺序表还是比较简单的一种数据结构,后续我会更新更多的数据结构。喜欢的就动动你可爱的小手点个赞!谢谢啦