単純な一方向リストです。
/*****************************************************************************/
/* 単純なリスト */
/*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node {
int no;
char str[256];
struct _node *next; /* 次のノードへのポインタ */
} Node_t;
#define OK 0
#define NG -1
/*****************************************************************************/
/* ノードのメンバに値設定 */
/*****************************************************************************/
static void SetNode(Node_t *node, int no, char *str, Node_t *next)
{
node->no = no;
strcpy(node->str, str);
node->next = next;
}
/*****************************************************************************/
/* ノードの領域確保 */
/*****************************************************************************/
static Node_t *AllocNode(void)
{
Node_t *node;
node = calloc(1, sizeof(Node_t));
return node;
}
/*****************************************************************************/
/* 先頭ノード挿入 */
/*****************************************************************************/
static int InsertNode(Node_t **head, int no, char *str)
{
Node_t *ptr = *head;
*head = AllocNode();
if (*head == NULL) {
return NG;
}
SetNode(*head, no, str, ptr);
return OK;
}
/*****************************************************************************/
/* 末尾ノード挿入 */
/*****************************************************************************/
int AppendNode(Node_t **head, int no, char *str)
{
int ret;
Node_t *ptr;
if (*head == NULL) {
ret = InsertNode(head, no, str);
if (ret != OK) {
return NG;
}
} else {
ptr = *head;
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = AllocNode();
if (ptr->next == NULL) {
return NG;
}
SetNode(ptr->next, no, str, NULL);
}
return OK;
}
/*****************************************************************************/
/* 全ノード表示 */
/*****************************************************************************/
void PrintAllNode(Node_t **head)
{
Node_t *ptr = *head;
while (ptr != NULL) {
printf("no = [%d], str = [%s]\n", ptr->no, ptr->str);
ptr = ptr->next;
}
}
/*****************************************************************************/
/* 先頭ノード削除 */
/*****************************************************************************/
static void FreeNode(Node_t **head)
{
Node_t *ptr;
if (*head != NULL) {
ptr = (*head)->next;
free(*head);
*head = ptr;
}
}
/*****************************************************************************/
/* 全ノード削除 */
/*****************************************************************************/
void FreeAllNode(Node_t **head)
{
while (*head != NULL) {
FreeNode(head);
}
}
使い方
int main(void)
{
Node_t *list = NULL; /* NULLで初期化すること */
int ret;
ret = AppendNode(&list, 1, "AAA");
if (ret != OK) {
return NG;
}
ret = AppendNode(&list, 2, "BBB");
if (ret != OK) {
return NG;
}
PrintAllNode(&list);
FreeAllNode(&list);
return OK;
}