数据结构是这样的:
typedef struct node { void *data; struct node *next; } node_t; typedef struct list { node_t *head; } list_t;
其中node_t 结构是操作封装的.
我想实现一个迭代器函数
int list_iter(list_t *,void *);
当循环达到list结束的时候返回0,否则返回1
也就是我可以这么使用iter:
while(list_iter(list,&data)){ //do something,such as get out data }
我想封装这个函数, 要用到static .但是static修饰的迭代节点指针不能很好的指示链表结束
typedef struct node { void *data; struct node *next; } node_t; typedef struct list { node_t *head; } list_t; #include <stdio.h> #include <malloc.h> int list_iter(list_t *list,void **data){ //若list指向空指针,直接退出 if(!list->head)return 0; *data = list->head->data; list->head = list->head->next; return 1; } int main(){ node_t node = {(void*)0xFFFFFFFF,0}; node_t *p = &node; list_t list = {&node}; void *data; int i; //初始化链表 for(i = 0; i < 10; ++i){ printf("filling data %p\n",2 * i + 1); p->next = malloc(sizeof *p); p = p->next; p->data = (void*)(2 * i + 1); } p->next = NULL; //使用迭代函数 while(list_iter(&list,&data)){ printf("%p\n",data); } return 0; }
你可以试试。不知你是不是这个意思。
我认为两个方案
1,在list_iter中每读出一个node销毁一个,直到某个node->next为null
2,扩展list_t,增加一个node_t *c_node。默认同head,每读一个向下走一个,直到null
int list_iter(list_t *list, void **data_ptr) { static node_t *p = NULL; static int flag = 0; if (!flag){ //p init to head node when the first time p = list->head; flag = 1; } if (!p){ flag = 0; return 0; } *data_ptr = p->data; p = p->next; return 1; }