题目
一、代码
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<string> v;
string s;
while(cin >> s) {
v.push(s);
}
cout << v.top();
v.pop();
while(!v.empty()) {
cout << " " << v.top(); // //一一配对,一空格一元素
v.pop();
}
return 0;
}
二、分析
本题应用栈,STL更简洁点。使用栈逆序输出,主要注意格式:一个元素+一个空格,最后元素无空格。因为使用栈,无法得知栈长度,无法像使用for循环
for(int i=0;i<n;i++){
cout<<i;
if(i<n) cout<<" ";
}
本题采用了:一空格+一元素格式。先输出一个元素,后按照格式输出剩余元素
cout << v.top();
v.pop();
while(!v.empty()) {
cout << " " << v.top(); // //一一配对,一空格一元素
v.pop();
}
值得总结。
补充:使用了while(cin >> s)
,输入结束时,在OJ里面会在输入文件结束后自动结束,如果是在IDE里面测试,会需要按ctrl + z,然后enter手动结束输入
本文主要参考了该博客