一方向リストその2。
リストの先頭と末尾へのポインタを用意する事で、
末尾へ効率的にノードを追加します。
/*****************************************************************************/
/* 線形リスト */
/*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node {
int no;
char str[256];
struct _node *next; /* 次のノード */
} Node_t;
typedef struct _list {
Node_t *head; /* リストの先頭 */
Node_t *tail; /* リストの末尾 */
} List_t;
#define OK 0
#define NG -1
/*****************************************************************************/
/* ノード領域確保 */
/*****************************************************************************/
Node_t *AllocNode(void)
{
Node_t *ptr;
ptr = (Node_t *)calloc(1, sizeof(Node_t));
return ptr;
}
/*****************************************************************************/
/* リストの初期化 */
/*****************************************************************************/
void InitList(List_t *list)
{
list->head = list->tail = AllocNode();
}
/*****************************************************************************/
/* 先頭ノード挿入 */
/*****************************************************************************/
int InsertNode(List_t *list, int no, char *str)
{
Node_t *ptr = list->head;
list->head = AllocNode();
if (list->head == NULL) {
return NG;
}
list->head->no = no;
strcpy(list->head->str, str);
list->head->next = ptr;
return OK;
}
/*****************************************************************************/
/* 末尾ノード挿入 */
/*****************************************************************************/
int AppendNode(List_t *list, int no, char *str)
{
Node_t *ptr = list->tail;
list->tail = AllocNode();
if (list->tail == NULL) {
return NG;
}
ptr->no = no;
strcpy(ptr->str, str);
ptr->next = list->tail;
return OK;
}
/*****************************************************************************/
/* 先頭ノード削除 */
/*****************************************************************************/
void DelNode(List_t *list)
{
Node_t *ptr;
if (list->head != list->tail) {
ptr = list->head->next;
free(list->head);
list->head = ptr;
}
}
/*****************************************************************************/
/* 全ノード削除 */
/*****************************************************************************/
void DelAllNode(List_t *list)
{
Node_t *ptr = list->head;
Node_t *ptr2;
while (ptr != list->tail) {
ptr2 = ptr->next;
free(ptr);
ptr = ptr2;
}
list->head = list->tail;
}
/*****************************************************************************/
/* 全ノード表示 */
/*****************************************************************************/
void PrintList(List_t *list)
{
Node_t *ptr;
ptr = list->head;
while (ptr != list->tail) {
printf("no = [%d], str = [%s]\n", ptr->no, ptr->str);
ptr = ptr->next;
}
}
使い方
int main(void)
{
/* 返却値のチェックは省略 */
List_t list;
InitList(&list);
AppendNode(&list, 1, "AAA");
AppendNode(&list, 2, "BBB");
AppendNode(&list, 3, "CCC");
PrintList(&list);
DelAllNode(&list);
return OK;
}