在使用链表是常用的指针向前后移动的情况,如果使用不当很容易写错,以下是看到的一种函数封装操作来实现的方式。
以下是在redis源码中看到的迭代函数:
listIter *listGetIterator(list *list, int direction)
{
listIter *iter;
if ((iter = zmalloc(sizeof(*iter))) == NULL) return NULL;
if (direction == AL_START_HEAD)
iter->next = list->head;
else
iter->next = list->tail;
iter->direction = direction;
return iter;
}
void listReleaseIterator(listIter *iter) {
zfree(iter);
}
listNode *listNext(listIter *iter)
{
listNode *current = iter->next;
if (current != NULL) {
if (iter->direction == AL_START_HEAD)
iter->next = current->next;
else
iter->next = current->prev;
}
return current;
}
用法示例:
listIter *iter;
iter = listGetIterator(list,<direction>);
while ((node = listNext(iter)) != NULL) {
doSomethingWith(listNodeValue(node));
}
listReleaseIterator(iter);
本文介绍了在Redis源码中用于在循环链表中前后移动指针的函数,包括`listGetIterator`、`listReleaseIterator`和`listNext`。这些函数方便地封装了迭代过程,确保正确操作链表节点。示例代码展示了如何使用这些函数进行迭代操作。

3406

被折叠的 条评论
为什么被折叠?



