数据结构与算法-队列

队列:队列与栈不同,它是一种先进先出的结构

实现
1、数组
2、链表

记录的数据
1、队首位置:第一个元素的位置
2、队尾位置:最后一个元素的位置
3、队列大小:size

这里写图片描述

队列操作

entryQueue():入队
exitQueue():出队
isQueueEmpty():队列为空
isQueueFull():队列满

队列的实现(顺序数组的实现)
将队列的定义放在queue.h中

class queue
{
    private:
        int size;
        int* a;
        int head;
        int tail;
    public:
        queue();
        ~queue();
        bool isQueueEmpty();
        bool isQueueFull();
        void entryQueue();
        int exitQueue();
        int getSize()
}

队列的具体实现:

#include<queue.h>
queue::queue(int size)
{
    a = new int[size];
    this->size = size;
    head=0;
    tail=0;
}
queue::~queue()
{
    delete[] a;
}
bool queue::isQueueEmpty()
{
    return (head == tail);
}
bool queue::isQueueFull()
{
    return tail+1 == size
}
void queue::entryQueue(int item)
{
    if(isQueueFull())
        print("the queue is full");
    else
        {
            a[tail ++] = item;
        }
}
int queue::exitQueue()
{
    if(isQueueEmpty())
        print("the queue is empty");
    else
        {
            int result = a[head];
            head = head+1;
            return result;
        }
}
int queue::getSize()
{
    return size;
}

上述使用顺序数组的形式实现了队列,但是这种方式有非常大的弊端:当删除队列中的元素时,数组中head之前空间我们无法再次使用,这样就造成了极大的空间浪费。解决的方法是使用循环队列或者直接使用链式存储。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值