开发者社区> 问答> 正文

单向链表如何实现一个迭代器函数

数据结构是这样的:

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修饰的迭代节点指针不能很好的指示链表结束

展开
收起
a123456678 2016-06-02 20:57:00 2205 0
1 条回答
写回答
取消 提交回答
  • 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;
    }
    2019-07-17 19:25:37
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载