c++ - 此 C++ 堆栈实现不产生任何输出
问题描述
void solve(int n, int a[]) {
stack<int> s;
s.push(a[0]);
for (int i = 1; i < n; i++) {
if (a[i] < s.top()) {
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << "\n";
} else {
s.push(a[i]);
cout << "\n";
}
}
}
这n
是数组的大小a[]
。它不会在控制台上产生任何输出。
示例输入:a[] = {3, 1, 2}
示例预期输出:
3
2 1
解决方案
- 您访问
s.top()
时没有检查是否s
为空,if (a[i] < s.top()) {
它导致分段错误。 - 在后者打印额外的换行符
cout << "\n";
。 - 小于先前值的值将被删除。
- 最后一块输入将不会被打印。
尝试这个:
void solve(int n , int a[]){
stack<int> s;
s.push(a[0]);
for(int i=1;i<n;i++){
if(!s.empty() && a[i] < s.top()){
while(!s.empty()){
cout << s.top() <<" ";
s.pop();
}
cout << "\n";
}
s.push(a[i]);
}
while(!s.empty()){
cout << s.top() <<" ";
s.pop();
}
cout << "\n";
}
或这个:
void flush_stack(stack<int>& s) {
while(!s.empty()){
cout << s.top() <<" ";
s.pop();
}
cout << "\n";
}
void solve(int n , int a[]){
stack<int> s;
s.push(a[0]);
for(int i=1;i<n;i++){
if(!s.empty() && a[i] < s.top()){
flush_stack(s);
}
s.push(a[i]);
}
flush_stack(s);
}
推荐阅读
- sql-server - xp_cmdshell 一直在后台运行
- bash - 如何将我的分布式 shell 脚本映射到 ansible
- java - 如何旋转 mp4 文件?
- html - 使用 XQuery 动态显示上一个/下一个 div - 递归?
- sql-server - 无法将类型“net.sourceforge.jtds.jdbc.ClobImpl”的属性值转换为所需类型“java.lang.String”
- php - 使用 Laravel 时如何删除 MongoDb json 中的属性
- python - 捕获游戏截图以供 Python 脚本使用
- arrays - 如何使用 find 函数知道索引的值?
- ios - 没有“decodeIfPresent”候选产生预期的上下文结果类型“[ModelMemberSubCategory]!”
- node.js - 测试失败时如何使 Newman 的节点脚本失败