EOJ 可旋栈

题目描述

在这里插入图片描述
用数组去模拟即可

#include <iostream>

using namespace std;

const int N = 1000000;

// 数组模拟栈(队列)
int hh, tt;
int stk[N];

int main() {
    int n = 0;
    cin >> n;
    hh = 300007, tt = 300007;
    int flag = 1;
    while(n --) {
        int a, x;
        cin >> a;


        if (a == 1) {
            // x入栈
            cin >> x;
            stk[tt] = x;
            if(flag > 0) tt ++;
            else tt --;
        }

        if (a == 2) {
            // 弹出栈顶元素
            if (flag > 0) tt --;
            else tt ++;
        }
        
        if (a == 3) {
            // cout << "Here: " << hh << " " << tt << endl; 
            // 翻转栈
            if (flag > 0) {
                if (hh < tt) {
                    int tmp = tt - 1;
                    tt = hh - 1;
                    hh = tmp;
                }
            }

            if (flag < 0) {
                if (hh > tt) {
                    int tmp = hh + 1;
                    hh = tt + 1;
                    tt = tmp;
                }
            }

            flag = flag * (-1); // -1表示倒着的
            // cout << "Here: " << hh << " " << tt << endl;
        }

        // 输出栈顶元素
        if ((flag > 0 && hh >= tt) || (flag < 0 && hh <= tt)) cout << -1 << endl;
        else if  ((flag > 0 && hh < tt) || (flag < 0 && hh > tt)) {
            if (flag > 0) cout << stk[tt - 1] << endl;
            else cout << stk[tt + 1] << endl;
        }
    }

    return 0;
}

发布了182 篇原创文章 · 获赞 71 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/103894676