首页 > 解决方案 > 为什么我用于在堆栈中打印最大元素的 C++ 代码没有产生正确的输出?

问题描述

我正在使用 C++ 进行编程练习最大元素( https://www.hackerrank.com/challenges/maximum-element/problem?isFullScreen=false ),练习的目标是打印每个类型 3 查询的最大元素. 每个查询都是以下三种类型之一:

  1. 将元素 x 压入堆栈。

  2. 删除堆栈顶部的元素。

  3. 打印堆栈中的最大元素。

对于输入:

10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3

预期输出为:

26
91

我的代码正在打印:

0
0

我的代码(写在下面)显然打印了错误的答案,但是我不知道我在哪里做错了。我该如何解决这个问题,或者调试我的错误?

#include<iostream>
#include<stack>
using namespace std;
int main() {
    int n;
    cin>>n;

    while(n--)
    {
        stack<int> s;
        int a;

        cin>>a;

        if(a==1)
        {
            int x;
            cin>>x;
            s.push(x);

        }
        else if (a==2)
        s.pop();

        else {
        int max =0;
        while(!s.empty())
        {
            if(s.top()>max)
            max=s.top();

            s.pop();

        }
        cout<<max<<endl;
        }
    }   
    return 0;
}

标签: c++stackmax

解决方案


stack<int> s; 您在循环内声明了堆栈,因此它将在循环的每次开始时被清除。声明应该在循环之外

stack<int> s; // move here, for example
int n;
cin>>n;
while(n--)
{
    // stack<int> s;

此更改将使此处输入的输出正确,但我认为仅此更改程序不正确。我不认为类型 3 查询应该删除堆栈中的元素。


推荐阅读