2014/08/15

簡單 Struct 清單的使用

這是一個簡單 Struct 的使用,資料餵入的方法只用單純的插入,暫時也還沒有遇到需求,所以就不寫搜尋跟刪除的功能了。

/**********
 * Define *
 * ********/

#define SLIST_ENTRY(s_type) struct s_type *next;

#define SLIST_IS_EMPTY(head) (head == NULL)

#define SLIST_NOT_EMPTY(head) (head != NULL)

#define SLIST_FOREACH(var, c_type, head) \
for (var=head; var!=NULL; var=var->next)

#define SLIST_INSERT(var, c_type, head) \
{
c_type *tail = head; \
var->next = NULL; \
if (NULL == tail) \
head = var; \
else \
{ \
while (tail && tail->next) \
tail = tail->next; \
if (tail) \
tail->next = var; \
} \
}

#define SLIST_FREE(c_type, head) \
if (head) \
{ \
c_type *this=head, *next; \
while (NULL != this) \
{ \
next = this->next; \
free(this); \
this = next; \
}; \
head = NULL; \
}

/***********
 * Example *
 * *********/

// Define Struct
typedef struct S_MyType
{
char FirstName[30];
char LastName[30];
SLIST_ENTRY(S_MyType);
} C_MyType;

// Define variable
C_MyType *Users;

// Insert Element
C_MyType *ptr = (C_MyType *)malloc(sizeof(C_MyType));
if (ptr)
{
ENSURE_ZERO(ptr, sizeof(C_MyType));
sprintf(ptr->FirstName, "Aim");
sprintf(ptr->LastName, "Wang");
SLIST_INSERT(ptr, C_MyType, Users);
}

// Read all data
C_MyType *ptr;
int i = 0;

SLIST_FOREACH(ptr, C_MyType, Users)
{
printf("User No.%2d: %s %s", i++, ptr->FirstName, ptr->LastName);
}

// release memory
SLIST_FREE(C_MyType, Users);

沒有留言: