顺序表动态
头文件SeqListD.h
#pragma once
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
typedef int DataType;
struct SeqListDynamic {
DataType *array;
int capacity;
int size;
};
typedef struct SeqListDynamic SeqListD;
// 等于下面的写法
/*
typedef struct SeqListDynamic {
DataType *array;
int capacity;
int size;
} SeqListD;
*/
#define CAPACITY (2)
// 动态顺序表的初始化
void SeqListDInit(SeqListD *pSLD);
// 销毁
void SeqListDDestroy(SeqListD *pSLD);
void ExpandIfRequired(SeqListD *pSLD);
// 尾插
void SeqListDPushBack(SeqListD *pSLD, DataType data);
// 头插
void SeqListDPushFront(SeqListD *pSLD, DataType data);
// 按下标插入
void SeqListDPushInsert(SeqListD *pSLD, int pos, DataType data);
// 打印
void SeqListDPrint(SeqListD *pSLD);
源文件SeqListD.c
#include "SeqListD.h"
// 动态顺序表的初始化
void SeqListDInit(SeqListD *pSLD)
{
assert(pSLD != NULL);
pSLD->capacity = CAPACITY;
pSLD->size = 0;
pSLD->array = (DataType *)malloc(pSLD->capacity * sizeof(DataType));
// pSLD->array = (DataType *)calloc(pSLD->capacity, sizeof(DataType));
assert(pSLD->array != NULL);
}
// 销毁
void SeqListDDestroy(SeqListD *pSLD)
{
assert(pSLD != NULL);
pSLD->size = 0;
// 这步最关键
free(pSLD->array);
pSLD->capacity = 0;
}
void ExpandIfRequired(SeqListD *pSLD)
{
if (pSLD->size < pSLD->capacity) {
return;
}
// 肯定不够
// 1. 容量变大
// 2. 开个新容量的空间
// 3. 把旧数据迁移到新空间
// 4. 把旧空间释放
// 5. 把新的空间挂过来
// realloc
// 伙伴算法
// 1.
pSLD->capacity *= 2;
// 2.
DataType *newArray = (DataType *)malloc(sizeof(DataType)* pSLD->capacity);
assert(newArray != NULL);
// 3.
int i;
for (i = 0; i < pSLD->size; i++) {
newArray[i] = pSLD->array[i];
}
// 4.
free(pSLD->array);
// 5.
pSLD->array = newArray;
}
// 尾插
void SeqListDPushBack(SeqListD *pSLD, DataType data)
{
assert(pSLD != NULL);
// 这是静态的处理的方式
//assert(pSLD->size < pSLD->capacity);
// 函数自己去判断,有必要就扩容
ExpandIfRequired(pSLD);
// 到这里的时候,容量肯定就够
pSLD->array[pSLD->size++] = data;
}
// 头插
void SeqListDPushFront(SeqListD *pSLD, DataType data)
{
assert(pSLD != NULL);
ExpandIfRequired(pSLD);
// 剩下的和静态的一样
int space;
for (space = pSLD->size; space > 0; space--) {
pSLD->array[space] = pSLD->array[space - 1];
}
pSLD->array[0] = data;
pSLD->size++;
}
// 按下标插入
void SeqListDPushInsert(SeqListD *pSLD, int pos, DataType data)
{
assert(pSLD != NULL);
ExpandIfRequired(pSLD);
// 把 [pos, size) 数据往后搬一格
int space;
for (space = pSLD->size; space > pos; space--) {
pSLD->array[space] = pSLD->array[space - 1];
}
pSLD->array[pos] = data;
pSLD->size++;
}
// 打印
void SeqListDPrint(SeqListD *pSLD)
{
int i;
for (i = 0; i < pSLD->size; i++) {
printf("%d ", pSLD->array[i]);
}
printf("\n");
}
void TestSeqListD()
{
SeqListD sld;
SeqListDInit(&sld);
SeqListDPushBack(&sld, 1);
SeqListDPushBack(&sld, 2);
SeqListDPushBack(&sld, 3);
SeqListDPushBack(&sld, 4);
SeqListDPrint(&sld);
SeqListDDestroy(&sld);
SeqListDPrint(&sld);
}
int main()
{
TestSeqListD();
system("pause");
return 0;
}