我想用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("%d\n", queueEmpty(q));
printf("%d\n", size(q));
return 0;
}
我不明白输出为0和1的原因,即队列为空且大小为0。
答案 0 :(得分:0)
您忘了调整q->dim
,因此在q->tail
之后1 % 1
仍为零(enqueue
)。