#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include "dlist.h" #include <assert.h> static DListRet str_upper(void* ctx, void* data) { char* p = (char*)data;
if (p != NULL) { while (*p != '\0') { if (islower(*p)) { *p = toupper(*p); } p++; } } return DLIST_RET_OK; }
static DListRet int_print(void* ctx, void* data) { printf("%d ", (int)data);
return DLIST_RET_OK; } static DListRet str_print(void* ctx, void* data) { printf("%s ", (char*)data);
return DLIST_RET_OK; }
void data_free(void* ctx, void* data) { free(data); }
static void demo_heap() { DList* dlist = dlist_create(data_free, NULL);
dlist_append(dlist, strdup("it")); dlist_append(dlist, strdup("is")); dlist_append(dlist, strdup("heap"));
dlist_traverse(dlist, str_upper, NULL); dlist_traverse(dlist, str_print, NULL);
dlist_destroy(dlist); }
typedef struct _MaxCtx { int is_first; int max; }MaxCtx;
static DListRet int_get_max(void* ctx, void* data) { MaxCtx* max_ctx = ctx; if (max_ctx->is_first) { max_ctx->is_first = 0; max_ctx->max = (int)data; } else if(max_ctx->max < (int)data) { max_ctx->max = (int)data; }
return DLIST_RET_OK; }
static DListRet int_get_sum(void* ctx, void* data) { long long* result = ctx; *result += (int)data; return DLIST_RET_OK; } void test_int(void) { int i = 0; void *p = NULL; long long sum = 0; MaxCtx max_ctx = {.is_first = 1, 0}; DList* dlist = dlist_create(NULL, NULL); for (i = 0; i < 5; i ++) { assert(dlist_append(dlist, (void*)i) == DLIST_RET_OK); } for (i = 0; i < 5; i ++) { assert(dlist_prepend(dlist, (void*)i) == DLIST_RET_OK); } assert(dlist_traverse(dlist, int_print, NULL) == DLIST_RET_OK); assert(dlist_get_by_index(dlist, 0, &p) == DLIST_RET_OK); printf("\n%d\n", (int*)p); assert(dlist_set_by_index(dlist, 3, (void*)i) == DLIST_RET_OK);
assert(dlist_get_by_index(dlist, 3, &p) == DLIST_RET_OK); printf("\n%d\n", (int*)p); assert(dlist_delete(dlist, 0) == DLIST_RET_OK); assert(dlist_delete(dlist, 3) == DLIST_RET_OK); assert(dlist_traverse(dlist, int_print, NULL) == DLIST_RET_OK); assert(dlist_traverse(dlist, int_get_sum, &sum) == DLIST_RET_OK); assert(dlist_traverse(dlist, int_get_max, &max_ctx) == DLIST_RET_OK); }
int main() { test_int(); demo_heap(); printf("\n \n"); return 0; }
|