首页 > 试题广场 >

FIFO队列

[编程题]FIFO队列
  • 热度指数:132 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
基于数组实现一个使用一个FIFO的队列,支持push和pop操作。并说明各项操作的复杂度。

输入描述:
第一行一个正整数n, (1<=n<=100000),表示操作的个数

接下来n行,每行有一个操作,

如果操作为push,则后面接一个正整数v(1<=v<=100000)表示push进队列的数;

如果操作为pop,则应输出pop出的数为多少。


输出描述:
对于每个pop操作,输出pop出的数为多少。
示例1

输入

10
push 60
pop
push 9
pop
push 27
pop
push 22
push 37
pop
push 100

输出

60
9
27
22
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int[] fifo = new int[100001];
        int start = 0;
        int end = 0;
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            String s = scanner.next();
            if (s.equals("push")) {
                int p = scanner.nextInt();
                fifo[end++] = p;
            } else if (s.equals("pop")) {
                System.out.println(fifo[start++]);
            }
        }
        scanner.close();
    }
}

发表于 2019-09-04 16:27:45 回复(2)
#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    while(cin >> n)
    {
        // 用vetor模拟实现就可以
        vector<int> fifo;
        while(n--)
        {
            string s1;
            cin >> s1;
            if(s1 == "push")
            {
                int val = 0;
                cin >> val;
                fifo.push_back(val);
            }
            else 
            {
                int val = fifo.front();
                fifo.erase(fifo.begin());
                cout << val << endl;
            }
        }
    }
    
    return 0;
}

发表于 2022-05-25 12:12:52 回复(0)
# -*- coding:utf-8 -*-
import sys
 
if __name__ == '__main__':
    n = int(input())
    m1 = []
    m2 = []
    while n > 0:
        res = sys.stdin.readline().split()
        if res[0] == 'push':
            m1.append(int(res[1]))
        if res[0] == 'pop':
            m2.append(m1.pop(0))
        n -= 1
    for i in m2:
        print(i)

发表于 2019-09-03 11:12:42 回复(0)