系统程序员成长计划003
#include "dlist.h" /* struct n{ int a; struct n *b; }x; x.a = 1; x.b = NULL; */ typedef struct _DListNode{ void* data; //<! 通用数据类型链表 struct _DListNode* pf; struct _DListNode* pn; }DListNode_t; //}DListNode_t, *pDListNode_t; //相当于typedef DListNode_t *pnode; DListNode_t* node_create(void* init) { DListNode_t* p = (DListNode_t*)malloc(sizeof(DListNode_t)); if(p){ p->data = init; p->pf = NULL; p->pn = NULL; } return p; } int node_insert(DListNode_t* thiz, DListNode_t* pins) { pins->pn = thiz->pn; pins->pf = thiz; if(thiz->pn != NULL){ thiz->pn->pf = pins; } thiz->pn = pins; return 0; } int node_delet(DListNode_t* thiz) { if(NULL == thiz) return 1; if(thiz->pf){ (thiz->pf)->pn = thiz->pn; } if(thiz->pn){ (thiz->pn)->pf = thiz->pf; } free(thiz); return 0; } DListNode_t* node_find(DListNode_t* head, void* target) { DListNode_t* q = head; for(;;){ if(target == q->data){ return q; } if(q->pn != NULL){ q = q->pn; }else{ break; } } return NULL; } int node_modify(DListNode_t* head, void* src, void* dest) { DListNode_t* p; p = node_find(head, src); if(p){ p->data = dest; return 0; } return 1; } /* 打印函数由用户传入,比如传入打印整数print_int的函数 */ void node_print(DListNode_t* head, pFunPrint pfunc_print) { DListNode_t* q = head; for(;;){ printf("node_addr: %p\r\n", q); pfunc_print(q->data); printf("node->pf: %p\r\n", q->pf); printf("node->pn: %p\r\n", q->pn); printf("\r\n"); if(q->pn != NULL){ q = q->pn; }else{ break; } } }
dlist.c
#ifndef __TEST_H #define __TEST_H #include <stdio.h> #include <string.h> #include <stdlib.h> typedef unsigned char uint8_t; //1 typedef unsigned short uint16_t; //2 typedef unsigned int uint32_t; struct _DListNode; typedef struct _DListNode DListNode_t; DListNode_t* node_create(void* init); int node_insert(DListNode_t* thiz, DListNode_t* pins); int node_delet(DListNode_t* thiz); DListNode_t* node_find(DListNode_t* head, void* target); int node_modify(DListNode_t* head, void* src, void* dest);
//定义需要用户传入的,打印回调函数指针 typedef void (*pFunPrint)(void* target); void node_print(DListNode_t* head, pFunPrint pfun_print); #endif
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "dlist.h" void print_int(void* data) { printf("%d\n", (int)data); } void main(void) { DListNode_t* p = node_create((void*)0); DListNode_t* p1 = node_create((void*)1); node_insert(p, p1); p1 = node_create((void*)2); node_insert(p, p1); p1 = node_create((void*)3); node_insert(p, p1); p1 = node_create((void*)4); node_insert(p, p1); p1 = node_create((void*)5); node_insert(p, p1);
/*这里为什么不直接用函数赋值?node_print(p, &print_int);
可能是,不修改函数调用形式:node_print(p, pfun);
只在外部对函数指针赋值
pfun_print = &print_int;
*/
pFunPrint pfun = &print_int; node_print(p, pfun); return; }
联我:shen5773384##163.com