/*
* File name: a15f3.c
------------------
*/
#include <stdio.h>
#define QueueLimit 11
typedef int QueueElementType;
typedef struct {
int Front, Rear;
int Count;
QueueElementType Element[QueueLimit];
} QueueType;
typedef enum { FALSE, TRUE } boolean;
void CreateQ(QueueType* Queue);
boolean EmptyQ(QueueType Queue);
boolean FullQ(QueueType Queue);
void RemoveQ(QueueType* Queue, QueueElementType* Item);
void AddQ(QueueType* Queue, QueueElementType Item);
void TraverseQ(QueueType Queue);
int main() {
//Variable declaration
QueueType Q;
QueueElementType Item;
int i, num;
CreateQ(&Q);
for (i = 3; i <= 30; i += 3)
AddQ(&Q, i);
printf("(a)\n");
TraverseQ(Q);
printf("(b)\n");
do {
printf("Give a number:");
scanf("%d", &num);
if ((num % 3) != 0)
printf("Give a multiple of 3\n");
} while ((num % 3) != 0);
AddQ(&Q, num);
TraverseQ(Q);
printf("(c)\n");
RemoveQ(&Q, &Item);
TraverseQ(Q);
printf("Removed item=%d\n", Item);
printf("(d)\n");
for (i = 0; i < 2; i++) {
do {
printf("Give a number:");
scanf("%d", &num);
if ((num % 3) != 0)
printf("Give a multiple of 3\n");
} while ((num % 3) != 0);
AddQ(&Q, num);
TraverseQ(Q);
}
printf("(e)\n");
while(!EmptyQ(Q)) {
RemoveQ(&Q, &Item);
TraverseQ(Q);
printf("Removed item=%d\n", Item);
}
return 0;
}
void CreateQ(QueueType* Queue) {
Queue->Front = 0;
Queue->Rear = 0;
Queue->Count = 0;
}
boolean EmptyQ(QueueType Queue) {
return (Queue.Count == 0);
}
boolean FullQ(QueueType Queue) {
return (Queue.Count == (QueueLimit - 1));
}
void RemoveQ(QueueType* Queue, QueueElementType* Item) {
if (!EmptyQ(*Queue))
{
*Item = Queue->Element[Queue->Front];
Queue->Front = (Queue->Front + 1) % (QueueLimit - 1);
Queue->Count--;
}
else
printf("Empty Queue\n");
}
void AddQ(QueueType* Queue, QueueElementType Item) {
if (!FullQ(*Queue))
{
Queue->Element[Queue->Rear] = Item;
Queue->Rear = (Queue->Rear + 1) % (QueueLimit - 1);
Queue->Count++;
}
else
printf("Full Queue\n");
}
void TraverseQ(QueueType Queue) {
int current;
printf("Queue: ");
if (!EmptyQ(Queue)) {
current = Queue.Front;
while (current != Queue.Count) {
printf("%d ", Queue.Element[current]);
current = (current + 1) % QueueLimit;
}
printf("\n");
printf("Front=%d Rear=%d Count=%d\n", Queue.Front, Queue.Rear, Queue.Count);
}
else printf("Empty Queue\n");
}
我有个问题.我想在队列中添加一些3的倍数,打印它们,然后逐个删除元素.尽管元素被正确地存储在它们在队列中的位置,但队列的遍历存在问题.如果您注意到队列的最后一个元素,当3被删除时,它不会显示在所有删除的屏幕上.有人能帮帮我吗?
预期结果如下: