[Algorithm Basics 19-Simulation Queue]

mock queue

Algorithm diagram

Algorithm Pseudocode

 example

Implement a queue, which is initially empty and supports four operations:

  1. push x– Insert a number x to the end of the queue;
  2. pop– Pop a number from the head of the queue;
  3. empty– Determine whether the queue is empty;
  4. query– Query the queue head element.

Now there are M operations to be performed on the queue, and each of operation 3 and operation 4 must output a corresponding result.

input format

The first line contains an integer M, representing the number of operations.

Next M lines, each line contains an operation command, and the operation command is one of push x, pop, .emptyquery

output format

For each emptyand queryoperation, a query result is output, and each result occupies one line.

Among them, emptythe query result of the operation is YESor NO, and querythe query result of the operation is an integer representing the value of the queue head element.

data range

1≤M≤100000,
1≤x≤109,
all operations are guaranteed to be legal.

Input sample:

10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6

Sample output:

NO
6
YES
4

Code

#include<iostream>
using namespace std;
const int maxn = 1000001;
int q[maxn],hh,tt=-1;

int main(){
    int M,k;
    string s;
    cin>>M;
    while(M --){
        cin>>s;
        if(s == "push"){
            cin>>k;
            q[++ tt] = k;
        }
        else if(s == "pop"){
            hh = hh + 1;
        }
        else if(s == "empty"){
            if(hh <= tt){
                cout<<"NO"<<endl;
            }
            else{
                cout<<"YES"<<endl;
            }
        }
        else{
            cout<<q[hh]<<endl;
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_60498436/article/details/132256782