关闭

用 union 将 单链表 模块化

518人阅读 评论(0) 收藏 举报
分类:

代码如下:

#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);
	
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:275122次
    • 积分:4227
    • 等级:
    • 排名:第7253名
    • 原创:152篇
    • 转载:101篇
    • 译文:0篇
    • 评论:10条
    最新评论