队列

131 阅读1分钟
  • 先进先出
  • 这里用数组来模拟栈

模板

普通队列

  • C++
// hh 表示队头,tt表示队尾的后一个位置
int q[N], hh = 0, tt = 0;

// 向队尾插入一个数
q[tt ++ ] = x;
if (tt == N) tt = 0;

// 从队头弹出一个数
hh ++ ;
if (hh == N) hh = 0;

// 队头的值
q[hh];

// 判断队列是否为空,如果hh != tt,则表示不为空
if (hh != tt)
{

}

循环队列

  • C++
// hh 表示队头,tt表示队尾的后一个位置
int q[N], hh = 0, tt = 0;

// 向队尾插入一个数
q[tt ++ ] = x;
if (tt == N) tt = 0;

// 从队头弹出一个数
hh ++ ;
if (hh == N) hh = 0;

// 队头的值
q[hh];

// 判断队列是否为空,如果hh != tt,则表示不为空
if (hh != tt)
{

}

练习

01 模拟队列

  • 题目

Snipaste_2023-03-01_22-57-11.png

  • 题解
import java.io.*;

public class Main {
    public static final int N = 100010;
    public static int[] q = new int[N];
    public static int hh = 0, tt = -1;
    public static int M;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        M = Integer.parseInt(br.readLine());

        while (M-- > 0) {
            String[] str1 = br.readLine().split(" ");
            if (str1[0].equals("push")) {
                q[++tt] = Integer.parseInt(str1[1]);
            } else if (str1[0].equals("pop")) {
                hh++;
            } else if (str1[0].equals("empty")) {
                if (hh <= tt) {
                    pw.println("NO");
                } else {
                    pw.println("YES");
                }
            } else {
                pw.println(q[hh]);
            }
        }

        pw.close();
        br.close();
    }
}