顺序表:
概念:
顺序表是线性表的一种实现方式,它是由一组连续的存储单元按照顺序排列的数据结构。顺序表中的元素在内存中的存储位置是连续的,可以通过元素的下标(索引)直接访问元素。因此,顺序表支持高效的随机访问,时间复杂度为 O(1)。
特点:
-
有序性:顺序表中的元素按照一定的顺序排列,每个元素都有唯一的位置。
-
有限性:顺序表的大小是固定的,它在创建时需要指定容量,并且不能自动扩容。如果要添加更多的元素,可能需要重新创建更大容量的顺序表,然后将原有元素拷贝到新表中。
-
直接访问:顺序表中的元素可以通过索引直接访问,也称为下标访问。通过下标访问元素的时间复杂度为 O(1)。
-
插入和删除效率低:在顺序表中,插入和删除元素的操作可能导致其他元素的移动,因此时间复杂度较高,为 O(n)。
实现方式:
可以通过数组实现
C语言代码实现:
建立:
typedef struct {
int data[MAX_SIZE]; // 用数组存储顺序表的元素
int length; // 记录顺序表中当前存储的元素个数
} SeqList;
插入元素:
bool Insert(SeqList* list, int index, int value) {
if (list->length >= MAX_SIZE || index < 0 || index > list->length) {
return false; // 插入失败,顺序表已满或索引不合法
}
for (int i = list->length - 1; i >= index; i--) {
list->data[i + 1] = list->data[i]; // 将 index 及其后的元素向后移动一位
}
list->data[index] = value; // 在 index 处插入新元素
list->length++; // 更新顺序表长度
return true;
}
删除元素:
bool Delete(SeqList* list, int index) {
if (index < 0 || index >= list->length) {
return false; // 删除失败,索引不合法
}
for (int i = index; i < list->length - 1; i++) {
list->data[i] = list->data[i + 1]; // 将 index 及其后的元素向前移动一位
}
list->length--; // 更新顺序表长度
return true;
}
查询元素:
int GetElement(SeqList* list, int value) {
for (int i = 0; i < list->length; i++) {
if (list->data[i] == value) {
return i; // 返回查询到的元素的下标
}
}
return -1; // 返回特定的值表示元素不存在
}
修改元素:
bool ModifyElement(SeqList* list, int index, int newValue) {
if (index < 0 || index >= list->length) {
return false; // 修改失败,索引不合法
}
list->data[index] = newValue; // 修改指定位置的元素值
return true;
}