提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、介绍
顺序表是一种基本的数据结构,其主要用途是存储一组具有相同类型的元素,并支持对这些元素的快速访问、插入、删除等操作。
顺序表适用于元素数量相对固定、操作次数较多的场景,例如需要频繁进行查找、排序、统计等操作的场景。其优点是具有较好的随机访问性能,可通过下标直接访问元素,并且支持连续存储,利于对内存空间的有效利用。
常见的应用场景包括:
- 数据库中的表格:表格中的每一行可以看作是一个元素,而表格的各个列则是元素的属性。在进行数据查询、排序、统计等操作时,可以使用顺序表进行存储和操作。
- 数组和向量:数组和向量中的元素通常具有相同的数据类型,并且需要支持快速访问、修改、插入、删除等操作。在这种情况下,可以使用顺序表作为底层数据结构,以提高数据操作效率。
- 计算机程序中的数据结构:在程序中,需要使用各种数据结构来存储和处理数据。顺序表可以作为栈、队列、堆等数据结构的底层实现,提供高效的数据存储和操作能力。
总之,顺序表作为一种基本的数据结构,具有广泛的应用场景,在计算机科学和软件工程领域有着重要的地位。
#include <stdio.h>
#include <stdlib.h>
#define Size 5
typedef struct Table {
int* head;
int length;
int size;
}table;
table initTable() {
table t;
t.head = (int*)malloc(Size * sizeof(int));
if (!t.head) {
printf("初始化失败");
exit(0);
}
t.length = 0;
t.size = Size;
return t;
}
table addTable(table t, int elem, int add)
{
if (add > t.length + 1 || add < 1) {
printf("插入位置有问题\n");
return t;
}
if (t.length == t.size) {
int* newHead = (int*)realloc(t.head, (t.size + 1) * sizeof(int));
if (!newHead) {
printf("存储分配失败\n");
return t;
}
t.head = newHead;
t.size += 1;
}
for (int i = t.length - 1; i >= add - 1; i--) {
t.head[i + 1] = t.head[i];
}
t.head[add - 1] = elem;
t.length++;
return t;
}
table delTable(table t, int add) {
if (add > t.length || add < 1) {
printf("被删除元素的位置有误\n");
return t;
}
//删除操作
for (int i = add; i < t.length; i++) {
t.head[i - 1] = t.head[i];
}
t.length--;
return t;
}
//查找函数,其中,elem表示要查找的数据元素的值,可以使用多种查找算法实现,比如说二分查找算法、插值查找算法
int selectTable(table t, int elem) {
for (int i = 0; i < t.length; i++) {
if (t.head[i] == elem) {
return i + 1;//由于返回的是元素在顺序表中的下标,所以+1就是该元素在数组中的位置是第几个
}
}
return -1;//如果查找失败,返回-1
}
//更改函数,其中,elem为要更改的元素,newElem为新的数据元素
table amendTable(table t, int elem, int newElem) {
int add = selectTable(t, elem);
t.head[add - 1] = newElem;//由于返回的是元素在顺序表中的位置,所以-1就是该元素在数组中的下标
return t;
}
void displayTable(table t) {
for (int i = 0; i < t.length; i++) {
printf("%d ", t.head[i]);
}
printf("\n");
}
int main() {
table t = initTable();
int a = 5;
//向顺序表中添加元素
for (int i = 1; i <= Size; i++) {
a = a + 5;
t.head[i - 1] = a;
t.length++;
}
printf("顺序表中存储的元素分别是:\n");
displayTable(t);
//在顺序表中插入元素
t = addTable(t, 99, 3);
printf("插入元素后,顺序表中存储的元素分别是:\n");
displayTable(t);
//在顺序表删除元素
t = delTable(t, 2);
printf("删除元素后,顺序表中存储的元素分别是:\n");
displayTable(t);
//在顺序表中查找元素
int selectnum;
selectnum = selectTable(t, 99);
printf("查找到的元素位置是:%d\n", selectnum);
//改
amendTable(t, 99, 88);
printf("改变元素后,顺序表中存储的元素分别是:\n");
displayTable(t);
return 0;
}
顺序表中存储的元素分别是:
10 15 20 25 30
插入元素后,顺序表中存储的元素分别是:
10 15 99 20 25 30
删除元素后,顺序表中存储的元素分别是:
10 99 20 25 30
查找到的元素位置是:2
改变元素后,顺序表中存储的元素分别是:
10 88 20 25 30