题解 | #句子逆序# | 栈的使用
句子逆序
http://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
string str;
string res;
stack<string> stk;
getline(cin, str); //输入一整行,防止空格断掉
for (int i = 0; i < str.size(); ++i)
{
if (str[i] != ' ')
res += str[i];
else
{
stk.push(res);
res = "";
}
if (i == str.size() - 1) //判断是否结束,将最后一个字符串存入栈中
stk.push(res);
}
while(!stk.empty()) //从栈顶开始输出
{
cout << stk.top() << " ";
stk.pop();
}
return 0;
}