#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int* elements; //指向整数数组的指针
size_t size; //当前数组中的元素数量
size_t capacity; //数组的总容量,即它可以容纳的最大元素数量
}SequentiaList;
void SequentiaListInit(SequentiaList* list, int capacity)
{
list->elements = (int*)malloc(sizeof(int) * capacity);
list->size = 0;
list->capacity = capacity;
}
void SequentiaListDestroy(SequentiaList* list)
{
if (list->elements) {
free(list->elements);
list->elements = NULL;
}
}
size_t SequentiaListSize(const SequentiaList* list)
{
return list->size;
}
//插入操作
void SequentiaListInsert(SequentiaList* list, int index, int element) //index是索引,element是元素
{
if (index<0 || index > list->size)
{
printf("Invalid index\n");
return;
}
if (list->size == list->capacity)
{
int* newElements = (int*)realloc(list->elements, sizeof(int) * list->capacity * 2);
if (newElements == NULL)
{
printf("Failed to allocate memory\n");
return;
}
list->elements = newElements;
list->capacity *= 2;
}
for (size_t i = list->size; i > index; --i)
{
list->elements[i] = list->elements[i - 1];
}
list->elements[index] = element;
++list->size;
}
//删除操作
void SequentiaListDelete(SequentiaList* list, int index)
{
if (index < 0 || index >= list->size)
{
printf("Invalid index\n");
return;
}
for (size_t i = index; i < list->size; ++i)
{
list->elements[i] = list->elements[i + 1];
}
--list->size;
}
//查找过程
size_t SequentiaListFind(SequentiaList* list, int element)
{
for (size_t i = 0; i < list->size; ++i)
{
if (list->elements[i] == element)
{
return i;
}
}
return -1;
}
//顺序表的索引
int SequentiaListIndex(const SequentiaList* list, int index)
{
if (index < 0 || index >= list->size)
{
printf("Invalid index\n");
return -1;
}
return list->elements[index];
}
//进行修改
void SequentiaListSet(SequentiaList* list, int index, int element)
{
if (index < 0 || index >= list->size)
{
printf("Invalid index\n");
return;
}
list->elements[index] = element;
}
int main()
{
SequentiaList list;
SequentiaListInit(&list, 1);
for (int i = 0; i < 10; ++i)
{
SequentiaListInsert(&list, i, i * 10);
}
printf("Size:%d\n", SequentiaListSize(&list));
int elem = SequentiaListIndex(&list, 2);//输出索引为2的元素
printf("%d %d\n", 2, elem);
int index = SequentiaListFind(&list, 15);
printf("%d %d\n", 15, index);
SequentiaListSet(&list, 3, 60);
for (int i = 0; i < SequentiaListSize(&list); ++i)
{
printf("%d %d\n", i, SequentiaListIndex(&list, i));
}
SequentiaListDestroy(&list);
}