I want to implement the queue ADT in C language.
I have the following:
// node structure:
typedef int ElementType;
typedef struct node {
ElementType key;
struct node* left_child;
struct node* right_sib;
}* Node;
typedef Node Item;
// queue structure:
struct queue {
Item* contents;
int head;
int tail;
int dim;
};
typedef struct queue* Queue;
Queue initqueue(); // create a queue
int queueEmpty(Queue q); // queue empty?
void enqueue(Queue q, Item elem); // insert item
int size(Queue q); // size of the queue?
Queue initqueue() {
Queue q = (Queue)malloc(sizeof(struct queue));
q -> contents = (Item*)malloc(sizeof(Item));
q -> head = 0;
q -> tail = 0;
q -> dim = 1;
return q;
}
int queueEmpty(Queue q) {
return (q -> head == q -> tail);
}
void enqueue(Queue q, Item elem) {
if (q -> head == (q -> tail % q -> dim) + 1 || q -> dim == 1)
q -> contents = (Item*)realloc(q -> contents, (q -> dim) * 2);
q -> contents[q -> tail] = elem;
q -> tail = (q -> tail + 1) % (q -> dim);
}
int size(Queue q) {
if (q -> tail < q -> head)
return ((q -> dim) - (q -> head) + (q -> tail) - 1);
else
return (q -> tail - q -> head);
}
int main() {
Queue q;
Item i = (Item)malloc(sizeof(struct node));
i -> key = 4;
q = initqueue();
enqueue(q, i);
printf("%d\n", queueEmpty(q));
printf("%d\n", size(q));
return 0;
}
I don't understand why the output is 0 and 1, that is the queue is empty and its size is 0.
You forgot to adjust
q->dim
, soq->tail
is still zero (1 % 1
) after theenqueue
.