目录
一、线性表
线性表是n个具有相同特性的数据元素的有限序列。 线性表是一种在实际中广泛使用的数据结构,常见的线性表:顺序表、链表、栈......
线性表在【逻辑上】是线性结构,也就是连续的一条直线; 但在【物理结构】上不一定是连续的,线性表在物理上储存时,通常是数组、链式结构等形式。
二、顺序表
1、概念
顺序表是线性表的一种。
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般采用数组存储。
【顺序表在逻辑结构、物理结构上都是线性的】
2、顺序表和数组区别
顺序表的底层结构是数组,对数组的封装,实现了常用的增删改查等接口。
三、分类
1、静态顺序表
2、动态顺序表
四、动态顺序表的实现
1、创立文件
2、顺序表的初始化和销毁
【SeqList.h】
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//定义动态顺序表结构
typedef int SLDatatype;
struct SeqList
{
SLDatatype* arr;
int capacity; //空间大小
int size; //有效数据个数
};
typedef struct SeqList SL; //给结构体SeqList改个名字SL
//顺序表的初始化
void SLInit(SL* ps);
//顺序表的销毁
void SLDestory(SL* ps);
【SeqList.c】
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"SeqList.h"
//顺序表的初始化
void SLInit(SL* ps)
{
ps->arr = NULL;
ps->size = ps->capacity = 0;
}
//顺序表的销毁
void SLDestory(SL* ps)
{
if (ps->arr) //相当于ps->arr != NULL
{
free(ps->arr);
}
ps->arr = NULL;
ps->size = ps->capacity = 0;
}
【test.c】
#include"SeqList.h"
void SLtest01()
{
SL s;
SLInit(&s);
SLDestory(&s);
}
int main()
{
SLtest01();
return 0;
}
3、打印
【SeqList.c】
void SLPrint(SL* ps)
{
for (int i = 0; i < ps->size; i++)
{
printf("%d ", ps->arr[i]);
}
printf("\n");
}
【test.c】
#include"SeqList.h"
void SLtest01()
{
SL s;
SLInit(&s);
SLPrint(&s);
SLDestory(&s);
}
int main()
{
SLtest01();
return 0;
}
4、判断空间是否足够
【SeqList.c】
//判断空间是否充足
void SLCheckCapacity(SL* ps)
{
//判断空间是否充足
if (ps->size == ps->capacity)
{
//增容 //0*2=0
//若capacity为0,给个默认值,否则x2倍
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);
}
ps->arr = tmp;
ps->capacity *= newCapacity;
}
}
5、头插
【SeqList.h】
//头插
void SLPushFront(SL* ps,SLDatatype x);
【SeqList.c】
//头插
void SLPushFront(SL* ps, SLDatatype x)
{
assert(ps);
//判断空间是否足够
SLCheckCapacity(ps);
//插入操作
//数据整体后移一位
f