一、顺序表

一、线性表

线性表(linearlist)是n个具有相同特性的数据元素的有限序列。线性表是⼀种在实际中⼴泛使⽤的数据结构,常⻅的线性表:顺序表、链表、栈、队列、字符串…
线性表在逻辑上是线性结构,也就说是连续的⼀条直线。但是在物理结构上并不⼀定是连续的,线性表在物理上存储时,通常以数组和链式结构的形式存储。
顺序表和链表都是线性表

二、顺序表

概念:顺序表是⽤⼀段物理地址连续的存储单元依次存储数据元素的线性结构,⼀般情况下采⽤数组存储
一、顺序表_第1张图片
顺序表的底层结构是数组,对数组的封装,实现了常⽤的增删改查等接⼝
顺序表和数组的区别:
一、顺序表_第2张图片

静态顺序表

概念:使⽤定⻓数组存储元素
一、顺序表_第3张图片
静态顺序表缺陷:空间给少了不够⽤,给多了造成空间浪费

动态顺序表

可以按需申请,不容易造成空间的浪费
一、顺序表_第4张图片

动态顺序表的实现

本文主要有一个头文件,两个源文件,会把函数的声明放在头文件中,这样就可以使函数在一个源文件中实现后,直接在另一个源文件中使用
头文件:

#pragma once
#include
#include
#include

//顺序表的结构
typedef int SLDataType;
typedef struct SeqList
{
	SLDataType* arr;
	int size;      //有效数据个数
	int capacity;  //空间大小
}SL;

//也可以写成:typedef struct SeqList SL;

//初始化
void SLInit(SL* ps);
//销毁
void SLDesTroy(SL* ps);

//尾插
void SLPushBack(SL* ps, SLDataType x);
//头插
void SLPushFront(SL* ps, SLDataType x);
//尾删
void SLPopBack(SL* ps);
//头删
void SLPopFront(SL* ps);

//查找
//找到了,返回下标;未找到,返回-1
int SLFind(SL* ps, SLDataType x);

//指定位置之前插⼊数据
void SLInsert(SL* ps, int pos, SLDataType x);
//指定位置删除数据
void SLErase(SL* ps, int pos);

上面是头文件的定义,下面则进行函数的实现

#include"SeqList.h"
//初始化
void SLInit(SL* ps) {
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}
//检查空间是否足够
void SLCheckCapacity(SL* ps) {
	if (ps->capacity == ps->size) {
		int new = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDataType* aa = (SLDataType*)realloc(ps->arr, new * sizeof(SLDataType));
		if (aa == NULL) {
			perror("aa");
			return 1;
		}
		ps->arr = aa;
		ps->capacity = new;
	}
}
//尾插
void SLPushBack(SL* ps, SLDataType x) {
	assert(ps);
	SLCheckCapacity(ps);
	ps->arr[ps->size++] = x;
}
//头插
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];
	}
	ps->arr[0] = x;
	++ps->size;
}
//尾删
void SLPopBack(SL* ps) {
	assert(ps && ps->size);
	--ps->size;
}
//头删
void SLPopFront(SL* ps) {
	assert(ps && ps->size);
	for (int i = 1; i < ps->size ; i++) {
		ps->arr[i - 1] = ps->arr[i];
	}
	--ps->size;
}
//查找位置
int SLFind(SL* ps, SLDataType x)
{
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
	}
	//未找到
	return -1;
}
//指定位置加入
void SLInsert(SL* ps, int pos, SLDataType x) {
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	++ps->size;
}
//指定位置删除
void SLErase(SL* ps, int pos) {
	assert(ps && ps->size);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	for (int i = pos; i<ps->size-1 ; i--)
	{
		ps->arr[i] = ps->arr[i+1];
	}
	--ps->size;
}
//销毁
void SLDesTroy(SL* ps) {
	if (ps->arr)
		free(ps->arr);
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

上面是函数的实现,如果想要使用这些函数,就需要在创建一个源文件,其中包含int main这个主函数,在进行使用

你可能感兴趣的:(链表)