# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
typedef struct Node
{
int data;
char ch;
}* PNODE, NODE;
typedef struct QUEUE
{
int maxsize;
int front;
int rare;
PNODE pBase;
}* PQUEUE, QUEUE;
//初始化
void init(PQUEUE pQ, int length)
{
pQ->maxsize = length;
pQ->pBase = (PNODE)malloc(sizeof(NODE) * length);
pQ->front = pQ->rare = 0;
while (!pQ->pBase)
{
printf("内存分配失败!\n");
exit(-1);
}
return;
}
//入队
void enqueue(PQUEUE pQ, int val, char ch)
{
if ((pQ->rare + 1) % (pQ->maxsize + 1) == pQ->front)
{
printf("队列满!%d, %c无法入队\n", val, ch);
return;
}
else
{
pQ->pBase[pQ->rare % pQ->maxsize].data = val;
pQ->pBase[pQ->rare % pQ->maxsize].ch = ch;
printf("入队元素:%d, %c\n", val, ch);
pQ->rare++;
}
return;
}
//遍历
void traverse(PQUEUE pQ)
{
for (int i = pQ->front; i < pQ->rare; i++)
{
printf("%d, %c\n", pQ->pBase[i % pQ->maxsize].data, pQ->pBase[i % pQ->maxsize].ch);
}
return;
}
//出队
void dequeue(PQUEUE pQ)
{
printf("出队元素:%d, %c\n", pQ->pBase[pQ->front], pQ->pBase[pQ->front]);
pQ->front++;
return;
}
int main(void)
{
QUEUE q;
init(&q, 10);
enqueue(&q, 0, 'z');
enqueue(&q, 1, 'y');
enqueue(&q, 2, 'x');
enqueue(&q, 3, 'w');
enqueue(&q, 4, 'v');
enqueue(&q, 5, 'u');
enqueue(&q, 6, 't');
enqueue(&q, 7, 's');
enqueue(&q, 8, 'r');
enqueue(&q, 9, 'q');
enqueue(&q, 10, 'p');
traverse(&q);
dequeue(&q);
traverse(&q);
enqueue(&q, 11, 'n');
traverse(&q);
dequeue(&q);
traverse(&q);
enqueue(&q, 12, 'm');
traverse(&q);
return 0;
}