STEP 4.1C リストを用いてスタック (演習問題2.6)

<問題> STEP3.2のリストを用いて、スタック操作を定義しなさい。


<実行例> (4.1Aと同じ実行です)
 
a is pushed
b is pushed
c is pushed

 List(Stack)
c
b
a

c is poped
b is poped

 List(Stack)
a

d is pushed
d is poped
e is pushed

 List(Stack)
e
a

(STEP3.2のlist.oを再利用できるので、list.cを再コンパイルしなくてもよい)

gcc -c list.c
gcc -c 0401.c
gcc -o 0401 list.o 0401.o



解答例
以下、0401c.c

#include "list.h"

/* insert, delete, accessを用いて、スタックの基本操作
pushdownとpopupを定義すればよい */

void pushdown (List *L, char x);
char popup (List *L);

/* プッシュとポップを(リスト関連関数を用いて/読み替えて)定義しよう */


/* プッシュは、1番目にインサートと同じ */
void pushdown (List *L, char x) {
   insert(L,1,x);
}

/* ポップは、1番目の値にアクセスしてから、1番目をデリートと同じ */
char popup (List *L) {
   char pop;
   pop = access(L,1);
   delete (L,1);
   return(pop);
}



int main(void){
   char x;
   List *L;
   L=create();

   pushdown(L,'a');
   printf("a is pushed \n");
   pushdown(L,'b');
   printf("b is pushed \n");
   pushdown(L,'c');
   printf("c is pushed \n");

   printf("\n List(Stack)");
   printlist(L);
   printf("\n");

   x=popup(L);
   printf("%c is poped \n", x);
   x=popup(L);
   printf("%c is poped \n", x);

   printf("\n List(Stack)");
   printlist(L);
   printf("\n");

   printf("d is pushed \n");
   pushdown(L,'d');
   x=popup(L);
   printf("%c is poped \n", x);
   pushdown(L,'e');
   printf("e is pushed \n");

   printf("\n List(Stack)");
   printlist(L);
   printf("\n");

/*
   while(!empty(L)){
      printf("%c",access(L,1));
      delete(L,1);
   }
   printf("\n");
*/
   FreeData(L);

   return(0);
}