Question:
C - Circular Queue?
Stephanie
2014-04-09 08:27:24 UTC
could anyone help me figure out the code for this question?
I need to write a code in C for:

int enqueue(*queue_t, int):

And what it does is:

Adds an int to the buffer. This function needs to return 1 when the character was successfully added and 0 when the buffer did not have room to add the character.
Three answers:
cja
2014-04-09 14:43:19 UTC
For a circular queue, there's usually not a concept of being "full", you just overwrite the oldest item, advance the head and tail indices/pointers, and keep going. If you're going to allow your circular queue to fill up, and you don't want to leave an unused element in your 'buffer' array, it gets a bit awkward. So, I added a 'full' attribute to your queue_t struct.



By the way, much of the code you've shown is nonsense. Queue_Size is always 32, so 'if (Queue_Size == 32)' is always true. Also, this syntax is wrong: void init_queue(*queue_t); It doesn't make sense to dereference a typedef.



Here's something that should help you get started:



#include

#include



#define Queue_Size 5

typedef enum { false = 0, true } bool;

typedef struct queue {

    int head;

    int tail;

    bool full;

    int buffer[Queue_Size];

} queue_t;



void init_queue(queue_t*);

int enqueue(queue_t*, int);

void displayQueue(const queue_t*);



int main(int argc, char *argv[]) {

    int i = 1;

    queue_t Q;



    init_queue(&Q);

    while (1) {

        if (enqueue(&Q, i++) == 1) {

            displayQueue(&Q);

        } else {

            puts("full");

            break;

        }

    }

    return 0;

}



void init_queue(queue_t *q) {

    q->head = q->tail = 0;

    q->full = false;

    memset(q->buffer, 0, sizeof(q->buffer));

}



int enqueue(queue_t *q, int n) {

    int inserted = 0, next = (q->tail + 1) % Queue_Size;



    if (!q->full) {

        q->buffer[q->tail] = n;

        q->tail = next;

        q->full = (next == q->head);

        inserted = 1;

    }

    return inserted;

}



void displayQueue(const queue_t *q) {

    int i = q->head;



    do {

        printf("%d ", q->buffer[i]);

        i = (i + 1) % Queue_Size;

    } while (i != q->tail);

    puts("");

}



#if 0



Program output:



1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

full



#endif
Vlar
2014-04-09 15:37:54 UTC
So you expect Y!A! to do your homework for you ... ? You haven't even attempted to answers the question.



1. how do you determine the size of the queue

2. what is the structure of the queue (queue_t)

3. how do you determine where to insert the new number
tbshmkr
2014-04-09 17:19:29 UTC
Post your code. Then people will be able to help you get it right.

=

Circular queue is the same as simple queue, The main difference is a circular queue last element will point to first element.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...