队列的实现

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

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

头文件

#pragma once        

#define ElemType int
#define QUEUE_SIZE  10

typedef 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;
}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值