c++ - 为什么我用于在堆栈中打印最大元素的 C++ 代码没有产生正确的输出?
问题描述
我正在使用 C++ 进行编程练习最大元素( https://www.hackerrank.com/challenges/maximum-element/problem?isFullScreen=false ),练习的目标是打印每个类型 3 查询的最大元素. 每个查询都是以下三种类型之一:
将元素 x 压入堆栈。
删除堆栈顶部的元素。
打印堆栈中的最大元素。
对于输入:
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;
}
解决方案
stack<int> s;
您在循环内声明了堆栈,因此它将在循环的每次开始时被清除。声明应该在循环之外
stack<int> s; // move here, for example
int n;
cin>>n;
while(n--)
{
// stack<int> s;
此更改将使此处输入的输出正确,但我认为仅此更改程序不正确。我不认为类型 3 查询应该删除堆栈中的元素。
推荐阅读
- java - 为什么 %I% 没有显示我的 JavaDoc 版本
- php - Laravel/PHP - 查询大数据和错误 500 的问题
- c# - 将输出和错误重定向到自定义 PSHostUserInterface
- asp.net-mvc - 如何在 ondblClickRow 事件中触发 beforeSubmitCell 事件
- php - PHP gettext 在 Homestead 中返回输入作为结果
- react-native - 不变违规:元素类型无效:期望字符串或类/函数,但得到:未定义。
- java - PriorityQueue 抛出类强制转换异常
- php - 获取外键值不是 id SQL
- javascript - *ngFor 强制按升序打印
- c# - *(decimal*)d=XXXm 导致另一个输出而不是 BinaryWriter.Write(XXXm)