顺序表的定义
typedef int DataType;
typedef struct seqList{
DataType* _array;
size_t _size;//unsigned int _size, 元素个数
size_t _capacity; //容量:当前可用空间
//unsigned int _capacity;
}seqList;
初始化
void seqListInit(seqList* sl){
//初始化数组
sl->_array = (int*)malloc(sizeof(DataType)* 4);
sl->_capacity = 4;
sl->_size = 0;
}
扩容函数
void checkCapacity(seqList* sl){
//增容
if (sl->_size == sl->_capacity){
sl->_capacity *= 2;
/*
//开空间
DataType* newArray = (DataType*)malloc(sizeof(DataType)* sl->_capacity);
//拷贝
memcpy(newArray, sl->_array, sl->_size * sizeof(DataType));
//释放空间
free(sl->_array);
sl->_array = newArray;
*/
sl->_array = (DataType*)realloc(sl->_array, sizeof(DataType)* sl->_capacity);
}
}
pushBack: 尾插
void seqListPushBack(seqList* sl, DataType value){
checkCapacity(sl);//检查是否需要扩容
sl->_array[sl->_size] = value;
size++;
//seqListInsert(sl, sl->_size, value),基于任意位置插入函数的尾插法
}
popBack: 尾删
void seqListPopBack(seqList* sl){
//不需要释放空间
//实质上是一种假删除,只是把要删除的数据,排出顺序表,并没有彻底删除掉
if (sl->_size){
sl->_size--;
}
//seqListErase(sl, sl->_size - 1),基于任意位置删除函数的尾删法
}
pushFront: 头插
void seqListPushFront(seqList* sl, DataType value){
checkCapacity(sl);//检查是否需要扩容
//元素移动需要从后向前移动, 防止元素覆盖
size_t end = sl->_size;
while (end > 0){
sl->_array[end] = sl->_array[end - 1];
end--;
}
sl->_array[0] = value;
sl->_size++;
//seqListInsert(sl, 0, value),基于任意位置插入函数的头插法
}
popFront: 头删
void seqListPopFront(seqList* sl){
//注意元素覆盖问题:
//移动: 从前向后移动
if (sl->_size){
size_t start = 1;// 1 ~ size - 1 ----> 0 ~ size - 2
while (start < sl->_size){
sl->_array[start - 1] = sl->_array[start];
start++;
}
sl->_size--;
}
//seqListErase(sl, 0),基于任意位置删除函数的头删法
}
在pos位置前面插入一个数据value
void seqListInsert(seqList* sl, size_t pos, DataType value){
//判断位置是否合法
if (pos <= sl->_size){
//检查容量
checkCapacity(sl);
//移动元素: pos ~ size-1
size_t end = sl->_size;
while (end > pos){
sl->_array[end] = sl->_array[end - 1];
end--;
}
sl->_array[pos] = value;
sl->_size++;
}
}
删除pos位置的数据
void seqListErase(seqList* sl, size_t pos){
if (pos < sl->_size){
// 移动元素: 从前向后移动
// 移动的位置: pos + 1 ~ size - 1 ---> pos ~ size - 2
size_t start = pos + 1;
while (start < sl->_size){
sl->_array[start - 1] = sl->_array[start];
start++;
}
sl->_size--;
}
}