线性表代码增删改查操作

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值