为什么我的C++;打印堆栈中最大元素的代码未生成正确的输出? 我正在使用C++编程程序>强>最大元素< /强>(),练习的目的是为每个类型3查询打印最大元素。 每个查询都是以下三种类型之一:
将元素x推入堆栈为什么我的C++;打印堆栈中最大元素的代码未生成正确的输出? 我正在使用C++编程程序>强>最大元素< /强>(),练习的目的是为每个类型3查询打印最大元素。 每个查询都是以下三种类型之一:,c++,stack,max,C++,Stack,Max,将元素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;
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;
}
#包括
#包括
使用名称空间std;
int main(){
int n;
cin>>n;
而(n--)
{
堆栈s;
INTA;
cin>>a;
如果(a==1)
{
int x;
cin>>x;
s、 推(x);
}
如果(a==2),则为else
s、 pop();
否则{
int max=0;
而(!s.empty())
{
如果(s.top()>最大值)
max=s.top();
s、 pop();
}
cout您在循环内部声明了堆栈stack s;
,因此它将在循环的每个开头被清除。声明应该在循环外部
stack<int> s; // move here, for example
int n;
cin>>n;
while(n--)
{
// stack<int> s;
stack s;//例如,移动到这里
int n;
cin>>n;
而(n--)
{
//堆栈s;
此更改将使此处输入的输出正确,但我认为仅此更改程序不正确。我不认为类型3查询应删除堆栈中的元素。您在循环中声明了堆栈,在这种情况下,每次递增或递减都会将值设置回初始状态
一个快速修复方法是只在循环外声明堆栈,其余代码看起来很好。1)将堆栈声明为循环外
2) 之前,元素被弹出以查找最大元素,因此创建了另一个堆栈以跟踪最大元素
新代码通过了所有测试用例:-
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s, max;
max.push(0);
int n;
cin >> n;
while (n--) {
int a;
cin >> a;
if (a == 1) {
int x;
cin >> x;
s.push(x);
if (x >= max.top())
max.push(x);
} else if (a == 2) {
int q = s.top();
if (q == max.top())
max.pop();
s.pop();
} else {
cout << max.top() << endl;
}
}
return 0;
}
#包括
#包括
使用名称空间std;
int main(){
堆栈s,最大值;
最大推力(0);
int n;
cin>>n;
而(n--){
INTA;
cin>>a;
如果(a==1){
int x;
cin>>x;
s、 推(x);
如果(x>=max.top())
最大推力(x);
}如果(a==2),则为else{
int q=s.top();
如果(q==max.top())
最大波普();
s、 pop();
}否则{
当您应该查找最大元素时,为什么要从堆栈中弹出呢?您可能应该只跟踪堆栈中当前的最大元素。#包括使用名称空间std;
-不。只是不。永远不要这样做。请立即阅读所有内容。我开始怀疑为其设置筛选器是否有意义包含#include
的帖子提示:已经存在。您不需要滚动自己的劣质版本。只需使用已经存在的内容即可。@cigien是的。让过滤器删除它们即可。。。