队列的实现

来源:互联网 发布:java 统计学 mahout 编辑:程序博客网 时间:2024/06/06 12:59

队列,又称为伫列(queue),是先进先出(FIFO, First-In-First-Out)的线性表。在具体应用中通常用链表或者数组来实现。队列只允许在后端(称为rear)进行插入操作,在前端(称为front)进行删除操作。队列的操作方式和堆栈类似,唯一的区别在于队列只允许新数据在后端进行添加。 ———维基百科

我们可以用队列完成很多的操作,比如二叉树的层次遍历,以及消息队列等等。
我们这次要介绍的是队列中的循环队列
由于循环队列无法简单的通过rear==front来判断队列是否已满,因此通常有两种方法来解决这个问题。
1.另设一个标志位来判断队列是“空”还是“满”
2.少用一个元素空间,约定以“队列头指针在队列尾指针的下一位置”作为队列已满的标志。标志

头文件

#pragma once        #define ElemType int#define QUEUE_SIZE  10typedef struct queue{    ElemType *base;          //队列中的对象    int capacity;                int front;    int rear;}queue;                       //创建队列的类型void init_queue(queue *q);      //初始化队列void push(queue *q, ElemType x);    //入队操作void pop(queue *q);             //出队ElemType gethead(queue *q);     //获取队首void show_queue(queue *q);      //遍历队列所有成员

头文件实现

#include<iostream>using namespace std;#include"queue.h"#include"assert.h"void init_queue(queue *q){    q->base = (ElemType *)malloc(sizeof(ElemType) * QUEUE_SIZE);    assert(q->base != NULL);    q->capacity = QUEUE_SIZE;    q->front = q->rear = 0;}void push(queue *q, ElemType x){    if((q->rear+1)%q->capacity == q->front)               {        cout<<"队列已满,"<<x<<"不能入队."<<endl;        return;    }    q->base[q->rear++] = x;    q->rear = q->rear % q->capacity;            //创建的为循环队列所以对capacity取模}void pop(queue *q){    if(q->front == q->rear)        return;    q->front++;    q->front = q->front % q->capacity;}ElemType gethead(queue *q){    assert(q->front != q->rear);    return q->base[q->front];}void show_queue(queue *q){    for(int i=q->front; i!=q->rear; )    {        cout<<q->base[i]<<" ";        i++;        i = i%q->capacity;    }    cout<<endl;}

主函数部分

#include<iostream>using namespace std;#include"queue.h"int main(){    int i;    queue q;    init_queue(&q);    for(i=0;i<10;i++)                 //因为循环队列需要空出一个存储单位,因此只能存到8    {        push(&q,i);                      }    show_queue(&q);    pop(&q);    pop(&q);    cout<<"head="<<gethead(&q)<<endl;}

这里写图片描述