顺序表接口的实现
程序员文章站
2024-03-20 13:51:10
...
typedef int SLDataType;
typedef struct SeqList{
SLDataType *data;
size_t size;
size_t capacity;
}SeqList;
实现
#include "List.h"
//初始化
void SeqListInit(SeqList* psl, size_t capacity){
assert(psl);
psl->capacity = capacity;
psl->size = 0;
psl->data = (SLDataType*)malloc(capacity * sizeof(SLDataType));
}
//销毁
void SeqListDestory(SeqList* psl){
assert(psl);
if (psl->data != NULL){
free(psl->data);
psl->data = NULL;
psl->size = 0;
psl->capacity = 0;
}
}
//检查容量
void CheckCapacity(SeqList* psl){
assert(psl);
if (psl->size == psl->capacity){
//重新开辟 2 倍
psl->data = (SLDataType *)realloc(psl->data, 2 * psl->capacity * sizeof(SLDataType));
psl->capacity = 2 * psl->capacity;
}
}
//尾插
void SeqListPushBack(SeqList* psl, SLDataType x){
assert(psl);
//检查容量
CheckCapacity(psl);
psl->data[psl->size] = x;
psl->size++;
}
//尾删
void SeqListPopBack(SeqList* psl){
assert(psl);
if (psl->size != 0){
psl->size--;
}
}
//头插
void SeqListPushFront(SeqList* psl, SLDataType x){
assert(psl);
//指定位置插入
SeqListInsert(psl, 0, x);
}
//头删
void SeqListPopFront(SeqList* psl){
assert(psl);
//指定位置删除
SeqListErase(psl, 0);
}
//查找
int SeqListFind(SeqList* psl, SLDataType x){
size_t i = 0;
for (i = 0; i < psl->size; i++){
if (psl->data[i] == x){
return i;
}
}
return -1;
}
//指定位置插入
void SeqListInsert(SeqList* psl, size_t pos, SLDataType x){
assert(psl);
if (pos > psl->size){
printf("越界");
return;
}
//检查容量
CheckCapacity(psl);
size_t i = 0;
//考虑size_t--;值为正的情况
for (i = psl->size; i > pos; i--){
psl->data[i] = psl->data[i - 1];
}
psl->data[pos] = x;
psl->size++;
}
//指定位置删除
void SeqListErase(SeqList* psl, size_t pos){
assert(psl);
if (pos >= psl->size){
printf("越界");
return;
}
size_t i = 0;
for (i = pos; i < psl->size; i++){
psl->data[i] = psl->data[i + 1];
}
psl->size--;
}
//指定值删除
void SeqListRemove(SeqList* psl, SLDataType x){
assert(psl);
size_t i = 0;
for (i = 0; i < psl->size; i++){
if (psl->data[i] == x){
//执行指定位置删除的操作
SeqListErase(psl, i);
break;
}
}
}
//指定位置修改
void SeqListModify(SeqList* psl, size_t pos, SLDataType x){
assert(psl);
if (pos >= psl->size){
printf("越界");
return;
}
psl->data[pos] = x;
}
//打印
void SeqListPrint(SeqList* psl){
size_t i = 0;
for (i = 0; i < psl->size; i++){
printf("%u ", psl->data[i]);
}
}
上一篇: cookie获取上次访问时间
下一篇: 浏览器Cookie获取和设置