我想用C语言实现队列ADT。
我有以下几点:
// 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("%dn", queueEmpty(q));
printf("%dn", size(q));
return 0;
}
我不明白为什么输出是 0 和 1,即队列为空,其大小为 0。
你忘了调整q->dim
,所以q->tail
在enqueue
之后仍然是零(1 % 1
)。