请问在这段代码中case1条件下,为什么程序先执行了GetTop(q)函数,后执行front(q)函数,导致输出结果发生如下错误:(运行在最新版visual studio平台)
queue = [ 40 87 34 96 84 99 58 ]
GetTop函数被调用!
pop 87 from queue = 1 # 每次pop的元素都是显示的是待出队列的元素的下一个元素
output函数被调用,q->head的值为:87
queue = [ 87 34 96 84 99 58 ]
GetTop函数被调用!
pop 34 from queue = 1 # 希望输出pop 87,结果因为函数调用顺序问题导致输出不对
output函数被调用,q->head的值为:34
queue = [ 34 96 84 99 58 ]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Queue {
int* data;
int head, tail;
int length, cnt;
} Queue;
Queue* init(int n) {
/*初始化队列*/
Queue* q = (Queue *)malloc(sizeof(Queue));
q->data = 0;
q->data = (int *)malloc(sizeof(int) * n);
q->head = q->tail = 0;
q->length = n;
return q;
}
int empty(Queue* q) {
// printf("q-head = %d, q->tail = %d, q->head == q->tail的值为:%d\n", q->head, q->tail, q->head == q->tail);
return q->head == q->tail;
}
/*查看队首元素*/
int front(Queue* q) {
if (empty(q))
return 0;
return q->data[q->head];
}
int push(Queue* q, int val) {
if (q == NULL)
return 0;
if (q->tail == q->length)
return 0;
q->data[q->tail++] = val;
printf("push %d 后 q->head : %d\n", val, front(q));
return 1;
}
/*头部元素出队列*/
int GetTop(Queue* q) {
printf("GetTop函数被调用!\n");
// printf("GetTop中empty(q)的值为:%d\n", empty(q));
if (q == NULL) {
printf("pop执行前q为NULL!\n");
return 0;
}
else if (empty(q)) {
printf("pop执行前q为空!\n");
return 0;
}
else {
// printf("pop执行前q->head : %d\n", front(q));
q->head++;
// printf("pop执行后q->head : %d\n", front(q));
return 1;
}
}
void clear(Queue* q) {
if (q == NULL)
return;
free(q->data);
free(q);
return;
}
void output(Queue* q) {
// printf("output函数被调用,q->head的值为:%d\n", front(q));
printf("queue = [");
for (int i = q->head; i < q->tail; i++) {
printf(" %d", q->data[i]);
}
printf(" ]\n");
return;
}
int main() {
srand(time(0));
#define MAX_OP 20
Queue* q = init(MAX_OP);
for (int i = 0; i < MAX_OP; i++) {
int val = rand() % 100;
int op = rand() % 2;
switch (op) {
case 0: {
printf("push %d to queue = %d\n", val, push(q, val));
} break;
case 1: {
printf("pop %d from queue = %d\n", front(q), GetTop(q));
} break;
}
output(q);
}
return 0;
}