您的位置:首页 > 其它

用 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);
	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: