#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
//
// 構造体の定義
struct c_list{
char ch; // 格納文字
struct c_list *pnext; // 次のデータのポインタ
};
// プロトタイプ宣言
void create(int n);
void removeall();
void push(struct c_list newdata);
struct c_list pop();
//
// リストの最初と最後のデータのポインタ
struct c_list *pnew;
//
// メイン関数
void main(){
struct c_list data;
char ch;
// バッファー作成
create(5);
// リスト作成
ch = getche();
while( isalpha(ch) ){
data.ch = ch;
push(data);
ch = getche();
}
// 改行
printf("\n");
// リスト表示
data = pop();
printf("%c\n", data.ch );
printf("\n");
// 確保した領域を開放する
removeall();
}
//
// 要素数n個の環状リスト(リングバッファ)を作る
void create(int n){
struct c_list *ptr;
// 0以下はありえない
if ( n <= 0 )
return;
// まず現在のリストを全て削除する
removeall();
// 1つめのバッファーを作る
pnew = (struct c_list*)malloc(sizeof( struct c_list ));
pnew->pnext = pnew;
// 2つめ以降のバッファーを作る
for ( ptr = pnew ; --n ; ptr = ptr->pnext ){
ptr->pnext = (struct c_list*)malloc(sizeof( struct c_list ));
}
// 最後のバッファーと最初のバッファーをつなげる
ptr->pnext = pnew;
}
//
// リストの全てを削除する
void removeall(){
struct c_list *ptr, *pnext;
// バッファーがなければ帰る
if ( !pnew )
return;
ptr = pnew;
do{
pnext = ptr->pnext;
free( ptr );
ptr = pnext;
}while( ptr != pnew && ptr );
pnew = NULL;
}
//
// データを代入する
void push(struct c_list newdata){
struct c_list *ptr;
// データ代入の準備
ptr = pnew->pnext;
newdata.pnext = ptr->pnext;
// データ代入
*ptr = newdata;
// 最新データの更新
pnew = ptr;
}
//
// リストの最初のデータを削除する
struct c_list pop(){
return *pnew;
}
|