#include "adlist.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<time.h>
int main()
{
struct list *t;
t=listCreate();
int i;
char *pb[5];
char buf[25];
srand(time(NULL));
char *pd;
for(i=0;i<5;i++)
{
//Method1:
//pb[i]=(char*)malloc(sizeof(char)*10);
//Method2:
pd=(char*)malloc(sizeof(char)*10);
sprintf(pd,"test index:%d.",rand()%100);
//Method3:
//memset(buf,0,25);
//char buf[25];
//sprintf(buf,"test index:%d.",rand()%100);
//这种方式不行,因为buf的地址在这个for loop里面始终没有发生变化,但是listAddNodeHead这个函数的实现是将buf的地址进行value传递的,
//因此当遍历list的时候,只能打印出最后listAddNodeHead的value.
//改进的方法是使用一个指针,对其进行loop一次,malloc一次,这样每个loop,地址都不一样。从而对应的链表中存放的地址也是不一样的。
//也可以是用指针数组的方法
t = listAddNodeHead(t,(void*)pd);
//t = listAddNodeTail(t,(void*)buf);
if(!t){
printf("listAddNodeHead error!\n");
exit(0);
}
printf("%s\n",pd);
//free(pb[i]);
//free(pd);
}
free(pd);
printf("\n");
listNode *p=NULL;
p=t->head;
if(p->prev==NULL){
printf("OK\n");
}
while(p!=NULL)
{
printf("%s\n",p->value);
p=p->next;
}
printf("\n");
/*p=t->tail;
if(p->next==NULL){
printf("OK\n");
}
while(p!=NULL)
{
printf("%s\n",p->value);
p=p->prev;
}
printf("\n");*/
// #define AL_START_HEAD 0
// #define AL_START_TAIL 1
listIter *it=NULL;
listNode *node=NULL;
it = listGetIterator(t,0);
while((node=listNext(it))!=NULL)
{
printf("%s\n",node->value);
listDelNode(t,node);
}
listReleaseIterator(it);
listRelease(t);
return 0;
}
这只是一个测试的文件,具体的内容请看redis的源代码。
Redis 中list的实现(地址传值)
最新推荐文章于 2023-05-22 14:32:18 发布