系统程序员成长计划002
#include "dlist.h" /* 封装 1.模块化文件分离,dlist.c/dlist.h/main.c 2.接口最小化不暴露类型定义给用户 */ /* struct n{ int a; struct n *b; }x; x.a = 1; x.b = NULL; */ typedef struct _DListNode{ int data; struct _DListNode* pf; struct _DListNode* pn; }DListNode_t; //}DListNode_t, *pDListNode_t; //相当于typedef DListNode_t *pnode; DListNode_t* node_create(int val) { DListNode_t* p = (DListNode_t*)malloc(sizeof(DListNode_t)); if(p){ p->data = val; 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, int val) { DListNode_t* q = head; for(;;){ if(val == q->data){ return q; } if(q->pn != NULL){ q = q->pn; }else{ break; } } return NULL; } int node_modify(DListNode_t* head, int src, int dest) { DListNode_t* p; p = node_find(head, src); if(p){ p->data = dest; return 0; } return 1; } void node_print(DListNode_t* head) { DListNode_t* q = head; for(;;){ printf("node_addr: %p\r\n", q); printf("node->dat: %d\r\n", 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
dlist.h文件只暴露链表的类型,外部只能使用这种类型的指针,不能确定这种类型的大小,不知道这种类型的成员。
#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(int val); int node_insert(DListNode_t* thiz, DListNode_t* pins); int node_delet(DListNode_t* thiz); DListNode_t* node_find(DListNode_t* head, int val); int node_modify(DListNode_t* head, int src, int dest); void node_print(DListNode_t* head); #endif
主程序main.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "dlist.h" void main(void) { DListNode_t* p = node_create(0); DListNode_t* p1 = node_create(1); node_insert(p, p1); p1 = node_create(2); node_insert(p, p1); p1 = node_create(3); node_insert(p, p1); p1 = node_create(4); node_insert(p, p1); p1 = node_create(5); node_insert(p, p1); node_print(p); printf("==============================\n"); p1 = node_find(p, 2); node_delet(p1); node_print(p); return; }
联我:shen5773384##163.com

浙公网安备 33010602011771号