用 union 将 单链表 模块化
2015-07-10 15:12
218 查看
代码如下:
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef unsigned int uint32_t; typedef char uint8_t; typedef unsigned short uint16_t; typedef struct _BOOK{ char name[32]; uint32_t price; }Book; typedef struct _Game{ char name[32]; uint32_t price; }Game; typedef union _messdata{ Book* book; Game* game; }messdata; typedef enum _messtype{ em_info_unable = 0, BOOK_TYPE = 1, GAME_TYPE }messtype; typedef struct __Msg { messdata node; //用联合将所有的变量都封装起来了 uint8_t type; struct __Msg* next; struct __Msg* pre; }Msg; typedef struct List{ Msg* msg; uint32_t list_len; Msg* head; Msg* cur; Msg* tail; }List; Msg *xmlmess_node_alloc(messtype type) { if (em_info_unable != type) { Msg *node = (Msg *)malloc(sizeof(Msg)); if (NULL != node) { node->type = type; node->next = NULL; switch (type) { case BOOK_TYPE: node->node.book = (Book *)malloc(sizeof(Book)); break; case GAME_TYPE: node->node.game = (Game *)malloc(sizeof(Game)); break; default: break; } } return node; } return NULL; } //create a list for xmlmess int create_list(List **pplist) { if (NULL != pplist) { List *listtemp = (List *)malloc(sizeof(List)); if (NULL != listtemp) { listtemp->head = listtemp->cur = listtemp->tail = NULL; listtemp->list_len = 0; *pplist = listtemp; return 0; } } return -1; } // add alist int append_list(List* list, Msg* node) { if(NULL == list || NULL == node) return -1; if (NULL == list->tail) { list->head= list->cur = list->tail = node; list->list_len = 1; } else { list->tail->next = node; list->tail = node; ++list->list_len; } return 1; } int travel_list(List* list) { if(list->list_len == 0) return ; else { Msg* tmp = list->head; while(tmp) { //printf("111111111\n"); tmp = tmp->next; } } } int main() { List* list = NULL; if( create_list(&list) < 0) printf("create list failed\n"); Msg* msg = xmlmess_node_alloc(BOOK_TYPE); msg->type = BOOK_TYPE; memcpy(msg->node.book->name, "lcf", 4); msg->node.book->price = 32; append_list(list, msg); travel_list(list); }
相关文章推荐
- 算法六:floyd-warshall和dijkstra
- WCF技术剖析之二十五: 元数据(Metadata)架构体系全景展现[WS标准篇]
- 常用日期格式符(表格)
- DWZ的选择带回功能无法带回第一个value中的值
- 关于spark ui中executor显示的内存量与设置的内存量不符的问题
- 模拟新浪微博随便看看
- Python函数式编程
- 内存区域划分
- MPI编译C++程序出现#error "SEEK_SET is #defined but must not be for the C++ binding of MPI" 的解决方法
- CF 340A The Wall
- 数据对齐
- C#流程控制语句
- C++学习网站总结[转]
- NYOJ5——Binary String Matching
- Android 开发新技术点评
- 悟空学Linux专栏----第19篇
- eclipse好用的快捷键
- 安装dlib python接口
- Hive去重复数据
- WCF技术剖析之二十四: ServiceDebugBehavior服务行为是如何实现异常的传播的?