线性表
线性表是数据结构中最基本且常用的一种形式,用于存储具有线性关系的数据元素。其特点是数据元素之间存在一对一的顺序关系。线性表(linear list)是n个具有相同特性的数据元素的有限序列。常见的线性表:顺序表、链表、栈、队列、字符串...
线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的,线性表在物理上存储时,通常以数组和链式结构的形式存储。
线性表支持以下常见操作:
-
初始化:创建一个空表。
-
插入:在指定位置插入元素。
-
删除:删除指定位置的元素。
-
查找:按值或位置查找元素。
-
更新:修改指定位置的元素值。
-
遍历:访问表中的每个元素。
-
求长度:返回表中元素的个数。
-
判断空表:检查表是否为空。
两种主要存储方式:

顺序表(顺序储存)
-
定义:用一组连续的内存单元依次存储数据元素。
-
特点:
-
随机访问:通过下标直接访问元素,时间复杂度为O(1)。
-
插入和删除效率低:需要移动大量元素,时间复杂度为O(n)。
-
存储密度高:仅存储数据元素,无需额外空间。
-
-
实现:通常使用数组。
-
类型:静态顺序表:使用定长数组存储元素。动态顺序表:使用动态开辟的数组存储。
//静态顺序表
struct SeqList
{
int arr[100];//定长数组
int size;//顺序表当前有效的数据个数
};
//动态顺序表
typedef struct SeqList
{
SLDataType* arr;
int size;//有效的数据个数
int capacity;//空间大小
}SL;
动态顺序表的实现 SeqList.h
#include <stdio.h>
#include <stdlib.h>
#include<assert.h>
//typedef int SLDataType;//方便后续类型的替换
typedef struct SeqList
{
SLDataType* arr;
int size;//有效的数据个数
int capacity;//空间大小
}SL;
//顺序表初始化
void SLInit(SL* ps);
//顺序表的销毁
void SLDestroy(SL* ps);
void SLPrint(SL s);
//头部插入/尾部插入
void SLPushBack(SL* ps, SLDataType x);
void SLPushFront(SL* ps, SLDataType x);
//尾部删除/头部删除
void SLPopBack(SL* ps);
void SLPopFront(SL* ps);
//指定位置之前插入/删除数据
void SLInsert(SL* ps, int pos, SLDataType x);
void SLErase(SL* ps, int pos);
//查找
int SLFind(SL* ps, SLDataType x);
SeqList.c
#include"SeqList.h"
void SLInit(SL* ps)
{
ps->arr= NULL;
ps->size = ps->capacity = 0;
}
void SLDestroy(SL* ps)
{
if (ps->arr)
{
free(ps->arr);
}
ps -> arr = NULL;
ps->size = ps->capacity = 0;
}
void SLCheckCapacity(SL* ps)
{
//插入数据之前先看空间够不够
if (ps->capacity == ps->size)
{
//申请空间
//增容
int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
SLDataType* tmp = (SLDataType*)realloc(ps->arr, newcapacity * sizeof(SLDataType));
if (tmp == NULL)
{
perror("realloc fail!");
exit(1);//直接退出程序,不再继续执行
//return;
}
//空间申请成功
ps->arr = tmp;
ps->capacity = newcapacity;
}
}
//尾插
void SLPushBack(SL* ps, SLDataType x)
{
温柔的方式
//if (ps == NULL)
//{
// return;
//}
assert(ps);//等价于assert(ps!=NULL)
SLCheckCapacity(ps);
ps->arr[ps->size++] = x;
//等价于
//ps->arr[ps->size]=x;
//++ps->size;
}
//头插
void SLPushFront(SL* ps, SLDataType x)
{
assert(ps);
SLCheckCapacity(ps);
//先让顺序表中已有的数据往后移动
for (int i = ps->size; i>0; i--)
{
ps->arr[i] = ps->arr[i - 1];//arr[1]=arr[0]
}
ps->arr[0] = x;
ps->size++;
}
//void SLPrint(SL s)
//{
// for (int i = 0; i < s.size; i++)
// {
// printf("%d ", s.arr[i]);
// }
// printf("\n");
//}
//尾删
void SLPopBack(SL* ps)
{
assert(ps);
assert(ps->size);
//顺序表不为空
//ps->arr[ps->size - 1] = -1;
--ps->size;
}
void SLPopFront(SL* ps)
{
assert(ps);
assert(ps->size);
//顺序表不