C++模拟队列的实现

C++模拟队列的实现,第1张

从零开始学数据结构(Day 6)

今天学习的是队列这一种数据结构,这种数据结构的应用十分的广泛,比如以后要学的单调队列,

以及堆的实现,都是基于基本的队列完成的。

我们主要用队列完成下面几种基本 *** 作:

实现一个队列,队列初始为空,支持四种 *** 作:

  1. push x – 向队尾插入一个数 ;
  2. pop – 从队头d出一个数;
  3. empty – 判断队列是否为空;
  4. query – 查询队头元素。

队列的特点:先进先出;(queue)

 上代码(代码有一个小问题,题主为了投机取巧,在查询时没有判断是否为空,因为我写的那道 题查询时是不会为空的

#include 
using namespace std;
int queue[100001], b = 1,e;
void push(int a)
{
    queue[++e] = a;
}
void pop()
{
    b++;
}
int empty()
{
    if(e-b < 0)
        return 0;
    else
        return 1;
}
int query()
{
        return queue[b];
}
int main()
{
    int m;
    cin >> m;
    string s;
    int a;
    while(m--)
    {
        cin >> s;
        if(s == "push")
        {
            cin >> a;
            push(a);
        }
        else if(s == "pop")
        {
            pop();
        }
        else if(s == "empty")
        {
            if(!empty())
                cout << "YES" << endl;
            else
                cout << "NO" << endl;
        }
        else if(s == "query")
        {
            cout << query() << endl;
        }
    }
    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/717284.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-25
下一篇2022-04-25

发表评论

登录后才能评论

评论列表(0条)

    保存