配列を使ったリスト - 改
上のコードだと、扱うデータが変更になった場合に書き直しづらい。
ex)topは要素の位置をint型で返すが、countが返すint型の値は要素数を表している。
この様な時は、プログラムとデータ型を分離して独立したデータ型として表現する。(抽象データ型-Abstract Data Type)
/* ** 配列を使ったリスト 改 */ #include <stdio.h> typedef int LIST_ITEM; /* リストの要素を表すデータ型 */ typedef int LIST_POS; /* リストの要素位置を表すデータ型 */ #define LIST_TAIL -1 /* リストの末尾 */ #define MAXSIZE 30 /* 配列のサイズ */ /* プロトタイプ */ void init(void); LIST_POS top(void); LIST_POS next(LIST_POS pos); LIST_ITEM count(void); LIST_ITEM item(LIST_POS pos); void add(LIST_ITEM value); void insert(LIST_POS pos, LIST_ITEM value); void delete(LIST_POS pos); void showList(int list[]); LIST_ITEM list[MAXSIZE]; LIST_POS tail; /* リストの末尾 */ int main(void) { int i; /* カウンタ */ init(); puts("要素を追加!"); for(i = 0 ; i < 5 ; i++){ add(i + 1); } showList(list); puts("初期化!"); init(); showList(list); for(i = 1 ; i <= 3 ; i++){ puts("要素を追加!"); add(i); } showList(list); puts("先頭の要素を削除!"); delete(top()); showList(list); puts("要素(99)を先頭に挿入!"); insert(top(), 99); showList(list); printf("listの要素数は%dです。\n", count()); return 0; } /* ** リストを初期化する */ void init(void) { tail = 0; } /* ** リストの先頭位置を返す */ LIST_POS top(void) { return 0; } /* ** 指定された位置の次の要素の位置を返す */ LIST_POS next(LIST_POS pos) { if(pos < tail - 1){ return pos + 1; }else{ return LIST_TAIL; } } /* ** 要素数を返す */ LIST_ITEM count(void) { return tail; } /* ** 指定された位置にある要素を返す */ LIST_ITEM item(LIST_POS pos) { if((0 <= pos) && (pos < tail)){ return list[pos]; }else{ return 0; } } /* ** 要素を追加する */ void add(LIST_ITEM value) { if(tail < MAXSIZE){ list[tail] = value; tail++; } } /* ** 要素を指定した位置に挿入する */ void insert(LIST_POS pos, LIST_ITEM value) { if((0 <= pos) && (pos < tail) && (tail < MAXSIZE)){ int i; /* カウンタ */ for(i = tail ; i > pos ; i--){ list[i] = list[i - 1]; } list[pos] = value; tail++; } } /* ** 要素を削除する */ void delete(LIST_POS pos) { if((0 <= pos) && (pos < tail)){ int i; /* カウンタ */ for(i = pos ; i < tail ; i++){ list[i] = list[i + 1]; } tail--; } } /* ** リストの中身を確認する */ void showList(int list[]){ int i; printf("list={"); for(i = top() ; i != LIST_TAIL ; i = next(i)){ if(i < tail - 1) printf("%d,", item(i)); else printf("%d", item(i)); } printf("}\n"); }