#include<stdio.h>
#include<stdlib.h>
typedef struct{
int* elements;
size_t size;
size_t capacity;
}SequentialList;
//初始化
void SequentialListInit(SequentialList* list,int capacity){
list->elements = (int*)malloc(sizeof(int) * capacity);
list->size = 0;
list->capacity = capacity;
}
//摧毁
void SequentialListDestroy(SequentialList* list){
if(list->elements){
free(list->elements);
list->elements = NULL;
}
}
//大小
size_t SequentialListSize(const SequentialList* list){
return list->size;
}
//插入
void SequentialListInsert(SequentialList* list,int index,int element){
if(index < 0 || index > list->size){
printf("无效索引\n");
return;
}
//扩容
if(list->capacity == list->size){
int* newelements = (int*)realloc(list->elements,sizeof(int*) * list->capacity*2);
if(newelements == NULL){
printf("扩容失败\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 SequentialListDelete(SequentialList* list,int index){
if(index < 0 || index >= list->size){
printf("无效索引\n");
return;
}
for(size_t i = index;i < list->size;++i){
list->elements[i] = list->elements[i+1];
}
list->size--;
}
//寻找元素索引
size_t SequentialListFind(const SequentialList* list,int element){
for(size_t i = 0;i < list->size;i++){
if(list->elements[i] == element){
return i;
}
}
return -1;
}
//寻找元素 通过索引
int SequentialListIndex(const SequentialList* list,int index){
if(index < 0 || index >= list->size){
printf("无效索引\n");
return -1;
}
return list->elements[index];
}
void SequentialListSet(SequentialList* list,int index,int element){
if(index < 0 || index >= list->size){
printf("无效索引\n");
return ;
}
list->elements[index] = element;
}
int main(){
SequentialList list;
SequentialListInit(&list,1);
for(int i = 0;i < 10;i++){
SequentialListInsert(&list,i,i * 10);
}
printf("Size: %d\n",SequentialListSize(&list));
int elem = SequentialListIndex(&list, 2);
printf("%d %d\n",2,elem);
int index = SequentialListFind(&list,15);
printf("%d %d\n",15,index);
SequentialListSet(&list,100,60);
SequentialListDelete(&list,3);
for(int i = 0;i < SequentialListSize(&list);i++){
printf("%d %d\n",i,SequentialListIndex(&list,i));
}
SequentialListDestroy(&list);
return 0;
}
顺序表模板
最新推荐文章于 2024-08-30 22:53:24 发布