I've given a code example that I've written that will create and fill a queue. That part is in the bottom most code section works ok. It's here for completeness.
I've some questions regarding circular queues for which I am having a difficult time wrapping my little mind around.
1) I need to create a function that clears the queue. So I wrote a function that does exactly what CreateQueue does. My question regarding this is wouldn't setting q->count to 0 do the same thing and is that really the more appropriate thing to do?
Code:
void ClearQueue(Queue *q){
q->count=0;
q->front=0;
q->rear=-1;
}
2) if I wanted to get to the front of the Queue, I guess I could just traverse backwards and decrement q->count until it reaches 0. Is that the correct approach?
3) Lastly, if you were asked to traverse the queue (God only knows why) but would you first make a copy of q->count, then reset to 0 and move through the queue incrementally till q->count = copy?
Thanks in advance,
Code:
Given the definitions:
#define MAXQUEUE 3
typedef char QueueEntry;
typedef struct queue{
int count;
int front;
int rear;
QueueEntry entry[MAXQUEUE];
} Queue;
// create the queue
void CreateQueue(Queue *q){
q->count=0;
q->front=0;
q->rear=-1;
}
//append items to the queue
void Append(QueueEntry x, Queue *q){
if(QueueFull(q))
Error("Cannot append an entry to a full queue");
else{
q->count++;
q->rear=(q->rear + 1) % MAXQUEUE;
q->entry[q->rear]=x;
}
}
//creates and fills the queue
int main(){
Queue q;
QueueEntry item;
CreateQueue(&q);
item='A';
Append(item, &q);
item='B';
Append(item,&q);
item='C';
Append(item,&q);
return 1;
}