1、队列就是一种先进先出的数据结构,一端插入元素,另一端取出元素。
#include <stdio.h>
#include <stdlib.h>
static int const QUEUE_INIT_SIZE = 10;
static int const QUEUE_INCREMENT = 10;
typedef char QElemType;
typedef struct MyQueue
{
QElemType * front;
QElemType * rear;
int queueSize;
int queueLength;
}MyQueueList;
//队头为空,队头出队,队尾进队
int initQueue(MyQueueList * queue){
queue->front = (QElemType *)malloc(QUEUE_INCREMENT * sizeof(QElemType));
if (!queue->front)
{
printf("队列初始化失败。\n");
return 0;
}
queue->rear = queue->front;
queue->queueSize = QUEUE_INIT_SIZE;
queue->queueLength = 0;
return 1;
}
int enterQueue(MyQueueList * queue, QElemType elem){
if (queue->rear - queue->front >= queue->queueSize)
{
queue->front = (QElemType *)realloc(queue->front, (queue->queueSize + QUEUE_INCREMENT) * sizeof(QElemType));
if (!queue->front)
{
printf("重新分配空间失败。\n");
return 0;
}
queue->rear = queue->front + queue->queueSize;
queue->queueSize += QUEUE_INCREMENT;
}
queue->rear++;
*(queue->rear) = elem;
queue->queueLength++;
return 1;
}
int outQueue(MyQueueList * queue, QElemType * elem){
if (queue->front == queue->rear)
{
printf("这是一个空队列。\n");
return 0;
}
*elem = *(queue->front + 1);
queue->queueLength--;
int i = 1;
while (queue->front + i <= queue->rear)
{
*(queue->front + i-1) = *(queue->front + i);
i++;
}
return 1;
}
int printQueue(MyQueueList * q){
if (q->front == q->rear)
{
printf("这是一个空队列。\n");
return 0;
}
for (int i = 0; i < q->queueLength; i++)
{
printf("%c", *(q->front+i+1));
}
printf("\n");
return 1;
}
int main(int argc, const char * argv[]){
MyQueueList queue;
initQueue(&queue);
for (int i = 0; i < 22; i++)
{
enterQueue(&queue, 'A' + i);
}
printQueue(&queue);
QElemType elem;
outQueue(&queue, &elem);
printf("出队列的元素是:%c\n", elem);
printQueue(&queue);
return 0;
}
输出:
ABCDEFGHIJKLMNOPQRSTUV
出队列的元素是:A
BCDEFGHIJKLMNOPQRSTUV
Program ended with exit code: 0