我创建了一个适用于任何数据类型的库:
List new_list(int,int);
创建新列表,例如:
List list=new_list(TYPE_INT,sizeof(int));
//This will create an list of integers
Error append(List*,void*);
将一个元素附加到列表中。 *追加accpts两个指针作为参数,如果要存储指向列表的指针,请不要通过指针传递指针
例如:
//using the int list from above
int a=5;
Error err;
err=append(&list,&a)
//for an list of pointers
List listptr=new_list(TYPE_CUSTOM,sizeof(int*));
int num=7;
int *ptr=#
append(&listptr,ptr);
//for list of structs
struct Foo
{
int num;
float *ptr;
};
List list=new_list(TYPE_CUSTOM,sizeof(struct Foo));
struct Foo x;
x.num=9;
x.ptr=NULL;
append(&list,&x);
错误获取(List*,int);
获取指定索引处的数据。调用时列表的当前指针将指向数据。
例如:
List list=new_list(TYPE_INT,sizeof(int));
int i;
for(i=1;i<=10;i++)
append(&list,&i);
//This will print the element at index 2
get(&list,2);
printf("%d",*(int*)list.current);
错误弹出(List*,int);
来自指定索引的弹出和元素
例如:
List list=new_list(TYPE_INT,sizeof(int));
int i;
for(i=1;i<=10;i++)
append(&list,&i);
//element in the index 2 will be deleted,
//the current pointer will point to a location that has a copy of the data
pop(&list,2);
printf("%d",*(int*)list.current);
//To use the list as stack, pop at index list.len-1
pop(&list,list.len-1);
//To use the list as queue, pop at index 0
pop(&list,0);
错误合并(List ,List);
合并两个相同类型的列表。如果类型不同,则会在它返回的 Error 对象中返回错误消息;
例如:
//Merge two elements of type int
//List 2 will come after list 1
Error err;
err=merge(&list1,&list2);
Iterator get_iterator(List*);
获取列表的迭代器。初始化时会有一个指向列表第一个元素的指针。
例如:
Iterator ite=get_iterator(&list);
Error next(Iterator*);
获取列表的下一个元素。
例如:
//如何迭代一个整数列表
Iterator itr;
for(itr=get_iterator(&list); ite.content!=NULL; next(ite))
printf("%d",*(int*)ite.content);
https://github.com/malayh/C-List