STEP 4.2C リストを用いてキュー (演習問題2.7)

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


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

 List(Queue)
a
b
c

a is dequeued
b is dequeued

 List(Queue)
c

d is enqueued
c is dequeued
e is enqueued

 List(Queue)
d
e

STEP3.2で、list.objがあるはず。再利用します。 (もう一度コンパイルするなら、gcc -o list.c )

今回作成した0402c.cだけコンパイル
gcc -c 0402.c
gcc -o 0401 list.o 0401.o



解答例
以下、0402c.c

#include "list.h"

void enqueue(List *L, char x);
char dequeue(List *L);

/* エンキューとデキューを、(リスト関係関数を用いて)定義 */

/* リストの一番最後に、インサート */
/* リストは、先頭と残り。残りもリストという性質を利用した再帰 */
void enqueue(List *L, char x) {
   if (L -> next != NULL){
      enqueue(L -> next,x); /* 残りのリストにエンキュー */
   } else {
      insert(L,1,x); /* 次がNULLなら、追加 */
   }
}

/* デキューは、先頭の要素の取り出し、削除 */
char dequeue(List *L) {
   char deq;
   deq = access(L,1);
   delete (L,1);
   return(deq);
}


int main(void){
   char x;
   List *L;
   L=create();
   enqueue(L,'a');
   printf("a is enqueued \n");
   enqueue(L,'b');
   printf("b is enqueued \n");
   enqueue(L,'c');
   printf("c is enqueued \n");

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

   x=dequeue(L);
   printf("%c is dequeued \n", x);
   x=dequeue(L);
   printf("%c is dequeued \n", x);

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

   enqueue(L,'d');
   printf("d is enqueued \n");
   x=dequeue(L);
   printf("%c is dequeued \n", x);
   enqueue(L,'e');
   printf("e is enqueued \n");

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

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

   FreeData(L);
   return(0);
}