栈和队列基础

来源:互联网 发布:雷诺数的特征长度知乎 编辑:程序博客网 时间:2024/06/06 03:45

这是一道关于栈和队列的水题,帮助熟悉自己的语法知识
作为第一篇博客文章,还是有点激动,嘿嘿。
题目如下(题目有删减 来自hdu 1702)
Each problem’s first line is a integer N(the number of commands), and a word “FIFO” or “FILO”.(you are very happy because you know “FIFO” stands for “First In First Out”, and “FILO” means “First In Last Out”).
and the following N lines, each line is “IN M” or “OUT”, (M represent a integer).
and the answer of a problem is a passowrd of a door, so if you want to rescue ACboy, answer the problem carefully!

Input
The input contains multiple test cases.
The first line has one integer,represent the number oftest cases.
And the input of each subproblem are described above.

Output
For each command “OUT”, you should output a integer depend on the word is “FIFO” or “FILO”, or a word “None” if you don’t have any integer.

Sample Input

4
4 FIFO
IN 1
IN 2
OUT
OUT
4 FILO
IN 1
IN 2
OUT
OUT
5 FIFO
IN 1
IN 2
OUT
OUT
OUT
5 FILO
IN 1
IN 2
OUT
IN 3
OUT

Sample Output

1
2
2
1
1
2
None
2
3

总结:
主要是掌握stack 和 queue的基本语法,这两个容器的特点很明显先进先出,先进后出所以很好记忆。
不过坑爹的是VS2017的坑爹,
1:新增的scanf_s对于字符串的输入必须要在后面标明预计输入的字符数目,(对于数字则没要求,字符也要),
2:而且标明的数字不得比定义的数组大小大,否则即使在操作过程中即使字符长度很小,没有越界。最后编译器也会出现stack around variable was corrupted这种错误。
下面是代码实现,

#include <stdio.h>#include <stack>#include <queue>using namespace std;int main() {    int cnt;    scanf("%d", &cnt);    while (cnt--) {        char str[8];        int a;        scanf("%d%s", &a, str);        //scanf_s("%d %s", &a, str);        if (str[2] == 'F') {            //first in first out            queue<int>que;            for (int i = 0; i < a; i++) {                scanf("%s", str);                if (str[0] == 'I') {                    int b=0;                    //data put in                    scanf("%d", &b);                    que.push(b);                }                else {                           //out                     if (que.empty())                        printf("None\n");                    else {                        printf("%d\n", que.front());                        que.pop();                    }                }            }        }        else {            stack<int> s;            for (int i = 0; i < a; i++) {                scanf("%s", str);                if (str[0] == 'I') {                    int b=0;                    scanf("%d", &b);                    s.push(b);                }                else {                    if (s.empty())                        printf("None\n");                    else {                        printf("%d\n", s.top());                        s.pop();                    }                }            }        }    }    return 0;}
原创粉丝点击