要素数0から次々追加させることはできますが、途中の追加ができません。
以下のプログラムは、ひとまず既存の配列の要素を表示させるデバッグ仕様となっています。
#include <stdio.h>
#include <stdlib.h>
/* セルの定義 */
struct Cell{
struct Cell *prev; //先頭のセル
struct Cell *next; //次のセル
int data; //データ
};
/* セルのリスト定義 */
struct CellList {
struct Cell *header; //先頭の要素
struct Cell *tail; //末尾の要素
int len; //リストの要素数
};
/* プロトタイプ宣言 */
void initList(struct CellList *cellList);
void addList(struct CellList *cellList, int data);
void deleteLastData(struct CellList *cellList);
void dump(struct CellList *cellList);
int isListEmpty(struct CellList *cellList);
/* リストの初期化 */
void initList(struct CellList *cellList) {
if (cellList == NULL) {
printf("[ERR]#initList list is empty\n");
return;
}
cellList->header = cellList->tail = NULL;
cellList->len = 0;
}
/* データをリストに追加 */
void addList(struct CellList *cellList, int data){
struct Cell *cell;
cell = (struct Cell *)malloc(sizeof(struct Cell));
/* データを記憶するための記憶領域を malloc で確保し、
その領域へのポインタを cell に代入する */
cell->data = data;
cell->next = NULL;
if (isListEmpty(cellList)) {
cell->prev = NULL;
cellList->len = 1;
cellList->header = cellList->tail = cell;
return;
}
cellList->tail->next = cell;
cell->prev = cellList->tail;
cellList->tail = cell;
cellList->len++;
}
/* 末尾のデータをリストから削除 */
void deleteLastData(struct CellList *cellList) {
if (isListEmpty(cellList)) {
printf("[ERR]#deleteLastData list is empty\n");
return;
}
// 要素1つの場合
if (cellList->len == 1 || cellList->tail == cellList->header) {
free(cellList->tail);
cellList->tail = cellList->header = NULL;
cellList->len = 0;
return;
}
cellList->tail = cellList->tail->prev;
free(cellList->tail->next);
cellList->tail->next = NULL;
cellList->len--;
}
/*
リストが空ならTrue、そうでないならFalseを返す
*/
int isListEmpty(struct CellList *cellList) {
return cellList == NULL || cellList->len == 0 || cellList->header == NULL || cellList->tail == NULL;
}
/* 全レコード表示 */
void dump(struct CellList *cellList){
if (isListEmpty(cellList)) {
printf("[ERR]#dump list is empty\n");
return;
}
struct Cell *cell = cellList->header;
printf("==========dump List========\n");
while(cell != NULL) {
printf("%d, ", cell->data);
cell = cell->next;
};
printf("\n===========================\n");
printf("dump List is %d\n", cellList->len);
}
/* メイン処理 */
int main(){
struct CellList cellList;
initList(&cellList);
int list[10] = {1, 0, 6};
// 空判定テスト
deleteLastData(&cellList);
int i;
for (i = 0; i < sizeof(list)/sizeof(list[i]); i++) {
addList(&cellList, list[i]);
}
dump(&cellList);
for (i = 0; i < sizeof(list)/sizeof(list[i]); i++) {
deleteLastData(&cellList);
}
dump(&cellList);
return 0;
}