1 、队列的定义
队列,英文名叫做queue,是一个种十分常见的数据结构。
在我们的生活中,处处可以看见队列,食堂中排队点餐,一个队伍就是一个队列;ATM排队取钱,也是一个队列。它们都有一个特点,就是先来的人先被服务。
FIFO,First In First Out,简单明了的说明了队列的特性,先进先出。根据这个排队的特点,我们也可以得出,队列只允许从一端插入(队尾),从一端出来(队头)。
2、队列的实现
队列其实是一种特殊的线性表。同线性表一样,它同样有两种实现方式:数组与链表。
让我们先看看数组是如何实现队列的。
#include<stdio.h> #include<malloc.h> typedef int QElemType; #define OK 1; #define ERROR 0; typedef struct Queue { QElemType data[6]; int front; int rear; } SqQueue; int main(void) { SqQueue queue; initQueue(&queue); enQueue(&queue, 1); enQueue(&queue, 2); enQueue(&queue, 3); enQueue(&queue, 4); readQueue(&queue); outQueue(&queue); readQueue(&queue); } int initQueue(SqQueue *Q) { Q->front = 0; Q->rear = 0; return OK; } int enQueue(SqQueue *Q, int value) { if(isFull(Q)){ printf("队列已满,不能再插入元素了!\n"); return ERROR; } Q->data[Q->rear] = value; Q->rear = (Q->rear+1) % 6; return OK; } QElemType outQueue(SqQueue *Q) { QElemType value; if (isEmpty(Q)) { printf("队列为空,出队失败!\n"); return ERROR; } value = Q->data[Q->front]; Q->front = (Q->front+1) % 6; return value; } int readQueue(SqQueue *Q) { int i = Q->front; printf("遍历队列:\n"); while(i != Q->rear) { printf("%d ", Q->data[i]); i = (i+1) % 6; } printf("\n"); return 0; } int isFull(SqQueue *Q) { if((Q->rear+1) % 6 == Q->front){ return OK; }else{ return ERROR; } } int isEmpty(SqQueue *Q) { if(Q->front == Q->rear){ return OK; } else { return ERROR; } }