1. 结构体定义
typedef struct {
int *data;
int length;
int maxSize;
}SqList;
2. 初始化
void SqListInit(SqList* sl)
{
sl->data = malloc(sizeof(int) * INIT_SIZE);
sl->length = 0;
sl->maxSize = INIT_SIZE;
}
3. 插入
int SqListInsert(SqList* sl, int pos, int e)
{
if(pos < 0 || pos > sl->length)
return -1;
if(sl->length == sl->maxSize) {
realloc(sl->data, sizeof(int) * (sl->maxSize + INCREMENT));
sl->maxSize += INCREMENT;
}
for(int i = sl->length;i > pos;i--)
sl->data[i] = sl->data[i - 1];
sl->data[pos] = e;
sl->length++;
return 0;
}
4. 删除
int SqListDelete(SqList* sl, int pos)
{
if(pos < 0 || pos > sl->length)
return -1;
for(int i = pos;i < sl->length - 1;i++)
sl->data[i] = sl->data[i + 1];
sl->length--;
return 0;
}
5. 按值查找
int SqListLocate(SqList* sl, int e)
{
for(int i = 0;i < sl->length;i++) {
if(sl->data[i] == e)
return i;
}
return -1;
}
|