前提
簡単なキューを実装しています。(リングバッファ)
実現したいこと
キューの機能は動作したのですが、
#define SIZE 5
としたにも関わらず、2文字しか入りません。
実行結果
$ ./a.exe q w ^Z q 1 4 2 4 w 3 4 4 4
該当のソースコード
c
1#define SIZE 5 2#include <stdio.h> 3#include <stdlib.h> 4typedef char elemtype; 5struct queue{ 6 int head, tail; 7 elemtype elem[SIZE]; 8}; 9 10void enqueue(struct queue *q, elemtype val){ 11 q->elem[q->tail] = val; 12 q->tail++; 13 if(q->tail >= SIZE){ 14 q->tail = 0; 15 } 16 if(q->tail == q->head){ 17 printf("queue overflow\n"); 18 exit(1); 19 } 20} 21 22elemtype dequeue(struct queue *q){ 23 elemtype val; 24 if(q->head == q->tail){ 25 printf("queue underflow\n"); 26 exit(1); 27 }else{ 28 val = q->elem[q->head]; 29 q->head++; 30 if(q->head >= SIZE){ 31 q->head = 0; 32 } 33 return val; 34 } 35} 36 37void initqueue(struct queue *q){ 38 q->head = q->tail = 0; 39} 40 41int queueempty(struct queue *q){ 42 return q->head == q->tail; 43} 44 45int main(void){ 46 struct queue buf; 47 elemtype e; 48 initqueue(&buf); 49 50 while(scanf("%c", &e)!=EOF){ 51 enqueue(&buf, e); 52 } 53 while(!queueempty(&buf)){ 54 printf("%c\n", dequeue(&buf)); 55 printf("%d %d\n", buf.head, buf.tail); 56 } 57 printf("\n"); 58 return 0; 59}
試したこと
試しにキューのヘッドとテイルも表示させました。なぜか1つの文字入力で2つ増えています。
回答2件
あなたの回答
tips
プレビュー