静态顺序表的定义
#define MAX_SIZE (100)
typedef int DataType;
typedef struct SeqList
{
DataType data[MAX_SIZE];
int size;
} SeqListR;
动态顺序表的定义
typedef int DDataType;
typedef struct
{
DDataType *array;//指针,指向一个顺序表
int size;//个数
int capacity;//容量相当于静态顺序表中的 MAX_SIZE
} SeqListD;
两种顺序表的对比
静态顺序表 | 动态顺序表 |
---|---|
大小是固定的(代码编写是就已经确定) | 可以在执行过程中动态控制顺序表的大小 |
结构体的布局(数组放在结构体内) | 数组存在堆上 |
/ | 动态内存管理 |
*结构体可以在堆上也可以在栈上
静态顺序表的相关功能见下面链接
https://blog.youkuaiyun.com/baidu_41813368/article/details/82770433
顺序表要实现的功能
动态顺序表除插入功能需要扩容,其余功能与静态的顺序表实现方式一样
void SeqListDInit(SeqListD *pSeq);//初始化
void SeqListDDestory(SeqListD *pSeq);//销毁
void PrintSeqList(const SeqListD *pSeq);//打印顺序表
void DPushBack(SeqListD *pSeq, DDataType data);//尾插
void PushFront(SeqListD *pSeq, DDataType data);//头插
void Insert(SeqListD *pSeq, int pos, DDataType data);//指定位置的插入
各项功能的具体实现
#include "SeqListDynamic.h"
#include <assert.h>
void SeqListDInit(SeqListD *pSeq)//初始化
{
const int init_capacity = 5;
assert(pSeq != NULL);
pSeq->size = 0;
pSeq->capacity = init_capacity;
pSeq->array = (DDataType *)malloc(sizeof(DDataType)*init_capacity);
assert(pSeq ->array);
}
void SeqListDDestory(SeqListD *pSeq)//销毁
{
free(pSeq->array);
pSeq->array = NULL;
pSeq->size = 0;
pSeq->capacity = 0;
}
void PrintSeqList(const SeqListD *pSeq)//打印顺序表
{
for (int i = 0; i < pSeq->size; i++)
{
printf(" %d ", pSeq->array[i]);
}
printf("\n");
}
void ExpandIfRequired(SeqListD *pSeq)//扩容
{
//不需要扩容
if (pSeq->size < pSeq->capacity)
{
return;
}
//需要扩容
int newCapacity = pSeq->capacity * 2;
DDataType *newArray = (DDataType *)malloc(sizeof(DDataType)* newCapacity);
assert(newArray);
//搬移老的数据到新的数组
for (int i = 0; i < pSeq->size; i++)
{
newArray[i] = pSeq->array[i];
}
//释放老的数组
free(pSeq->array);
//新数组放到顺序表结构体里
pSeq->array = newArray;
//更新 capacity
pSeq->capacity = newCapacity;
}
void DPushBack(SeqListD *pSeq ,DDataType data)//尾插
{
assert(pSeq);
ExpandIfRequired(pSeq);
pSeq->array[pSeq->size++] = data;
}
void PushFront(SeqListD *pSeq, DDataType data)//头插
{
assert(pSeq);
ExpandIfRequired(pSeq);
for (int i = pSeq->size - 1; i >= 0; i--)//i的含义是数据的下标
{
pSeq->array[i + 1] = pSeq->array[i];
}
//for (int j = pSeq->size; j > 0; j--)//j的含义是空间的下标
//{
// pSeq->array[j] = pSeq->array[j - 1];
//}
pSeq->array[0] = data;
pSeq->size++;
}
void Insert(SeqListD *pSeq, int pos, DDataType data)//指定位置的插入
{
assert(pSeq);
ExpandIfRequired(pSeq);
assert(pos >= 0 && pos <= pSeq->size);
for (int i = pSeq->size; i >= pos + 1; i--)//i的含义是数据的下标
{
pSeq->array[i] = pSeq->array[i - 1];
}
pSeq->array[pos] = data;
pSeq->size += 1;
}
如有不足之处,欢迎指正!!