这段代码将简单的队列数据结构作为数组实现
#include <stdio.h>
#define Q_MAX_SIZE 255
#include <stdbool.h>
struct queue
{
int* pointer;
int* currentValue;
int max, count, theQueue[Q_MAX_SIZE];
};
void initQueue(struct queue*);
bool pushQueue(struct queue*, int);
int* popQueue(struct queue*);
int main(void)
{
int i, j, num = 0;
struct queue obj[5];
for(i=0; i<5; i++)
{
initQueue(&obj[i]);
for(j = 0; j<3; j++)
{
num++;
pushQueue(&obj[i], num);
}
num = 0;
}
for(i=0; i<5; i++)
{
printf("Queue[%d]:\n", i);
int* inputobj;
inputobj = popQueue(&obj[i]);
while(inputobj != NULL)
{
printf("Queue[No.%d] = %d\n", i, *inputobj);
inputobj = popQueue(&obj[i]);
}
putchar('\n');
}
puts("done..!");
return 0;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void initQueue(struct queue *Q)
{
Q->pointer = Q->theQueue;
Q->max = Q_MAX_SIZE;
Q->count = 0;
}
bool pushQueue(struct queue *Q, int input)
{
if(Q->count < Q->max)
{
*Q->pointer = input;
Q->pointer++;
Q->count++;
return 1;
}
else
return 0;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int* popQueue(struct queue *Q)
{
int i;
if(Q->count > 0)
{
Q->currentValue = Q->theQueue;
Q->pointer--;
Q->count--;
for(i=0; i < Q->count; i++)
{
int* currentPtr = Q->theQueue + i;
int* nextPtr = currentPtr + 1;
*currentPtr = *nextPtr;
}
return Q->currentValue;
}
else
NULL;
}
这行函数中的代码有问题popQueue()
:
Q->currentValue = Q->theQueue;
这是工作,输出不正确
output:
Queue[0]:
Queue[No.0] = 2
Queue[No.0] = 3
Queue[No.0] = 3
Queue[1]:
Queue[No.1] = 2
Queue[No.1] = 3
Queue[No.1] = 3
Queue[2]:
Queue[No.2] = 2
Queue[No.2] = 3
Queue[No.2] = 3
Queue[3]:
Queue[No.3] = 2
Queue[No.3] = 3
Queue[No.3] = 3
Queue[4]:
Queue[No.4] = 2
Queue[No.4] = 3
Queue[No.4] = 3
done..!
但是在我更改结构currentValue
中的指针 ()queue
使其成为整数类型并编辑函数中的一些行之后,popQueue()
一切正常。
--编辑后的函数如下:
int* popQueue(struct queue *Q)
{
int i;
if(Q->count > 0)
{
Q->currentValue = Q->theQueue[0];
Q->pointer--;
Q->count--;
for(i=0; i < Q->count; i++)
{
int* currentPtr = Q->theQueue + i;
int* nextPtr = currentPtr + 1;
*currentPtr = *nextPtr;
}
return &Q->currentValue;
}
-- 这是正确的输出:
Queue[0]:
Queue[No.0] = 1
Queue[No.0] = 2
Queue[No.0] = 3
Queue[1]:
Queue[No.1] = 1
Queue[No.1] = 2
Queue[No.1] = 3
Queue[2]:
Queue[No.2] = 1
Queue[No.2] = 2
Queue[No.2] = 3
Queue[3]:
Queue[No.3] = 1
Queue[No.3] = 2
Queue[No.3] = 3
Queue[4]:
Queue[No.4] = 1
Queue[No.4] = 2
Queue[No.4] = 3