以下是我写完之后又找大佬优化后的代码:
#include <stdio.h>
#include <stdlib.h> // 引入用于动态内存分配的头文件
typedef int ElemType;
typedef struct
{
ElemType* data; // 将数组改为指针,以便动态分配内存
int capacity; // 存储当前分配的容量
int length; // 存储当前已使用的长度
} SqList;
// 初始化顺序表(动态分配初始容量)
void InitList(SqList* L, int initialCapacity /*= 10*/)
{
if (initialCapacity <= 0) initialCapacity = 10;
L->data = (ElemType*)malloc(initialCapacity * sizeof(ElemType));
if (!L->data) { perror("Failed to allocate memory"); exit(EXIT_FAILURE); }
L->capacity = initialCapacity;
L->length = 0;
}
// 销毁顺序表(释放内存)
void DestroyList(SqList* L)
{
free(L->data);
L->data = NULL;
L->capacity = 0;
L->length = 0;
}
// 获取顺序表长度
int GetLength(SqList* L)
{
return L->length;
}
// 获取指定位置的元素
int GetElem(SqList* L, int i, ElemType* e)
{
if (i < 1 || i > L->length)
return 0;
*e = L->data[i - 1];
return 1;
}
// 定位元素
int Locate(SqList* L, ElemType x)
{
int i = 0;
while (i < L->length && L->data[i] != x)
{
i++;
}
if (i >= L->length)
return 0;
else
return i + 1;
}
// 插入元素,并自动扩容
int InsElem(SqList* L, ElemType x, int i)
{
if (i < 1 || i > L->length + 1)
return 0;
// 如果即将达到当前容量,先扩容
if (L->length >= L->capacity) {
ResizeList(L, L->capacity ? L->capacity * 2 : 1);
}
// 移动元素并将新元素插入
for (int j = L->length - 1; j >= i - 1; --j)
{
L->data[j + 1] = L->data[j];
}
L->data[i - 1] = x;
L->length++;
return 1;
}
// 扩容函数
void ResizeList(SqList* L, int newCapacity)
{
ElemType* newData = (ElemType*)realloc(L->data, newCapacity * sizeof(ElemType));
if (!newData) { perror("Failed to reallocate memory"); exit(EXIT_FAILURE); }
L->data = newData;
L->capacity = newCapacity;
}
// 删除元素
int DelElem(SqList* L, int i)
{
if (i < 1 || i > L->length)
return 0;
// 移动后续元素
for (int j = i; j < L->length; ++j)
{
L->data[j - 1] = L->data[j];
}
L->length--;
return 1;
}
// 输出顺序表元素
void DispList(SqList* L)
{
for (int i = 0; i < L->length; i++)
{
printf("%d ", L->data[i]);
}
printf("\n");
}
int main()
{
int i;
ElemType e;
SqList L;
InitList(&L);
InsElem(&L, 1, 1);
InsElem(&L, 3, 2);
InsElem(&L, 5, 4);
InsElem(&L, 4, 5);
InsElem(&L, 2, 6);
printf("线性表: ");
DispList(&L);
printf("长度: %d\n", GetLength(&L));
i = 3;
if (GetElem(&L, i, &e))
{
printf("第%d 个元素: %d\n", i, e);
}
if (Locate(&L, 1) == 1)
{
printf("元素1是第%d 个元素\n", Locate(&L, 1));
}
if (DelElem(&L, 4))
{
printf("删除第%d 个元素\n", 4);
}
printf("线性表: ");
DispList(&L);
DestroyList(&L);
return 0;
}
真的费了我很大功夫,我觉得已经很完整了,希望大家看完之后有所收获,感谢大家。