1009 说反话 (20 分)
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子。
输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
解题思路:(三种)
C++版
第一种:利用stack种栈的先进后出的原理
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
stack<string> ch;
string s;
while(cin>>s)
ch.push(s);
cout<<ch.top();
ch.pop();
while(!ch.empty())
{
cout<<' '<<ch.top();
ch.pop();
}
//system("pause");
return 0;
}
第二种:利用vector容器
#include<iostream>
#include<stdlib.h>
#include<string>
#include<vector>
using namespace std;
int main()
{
string ch;
vector<string> a;
while(cin>>ch)
{
a.push_back(ch);
}
int num = a.size();
cout<<a[num - 1];
for(int i = num -2; i >= 0; i-- )
{
cout<<' '<<a[i];
}
return 0;
}
第三种:利用map键值对
#include<iostream>
#include<stdlib.h>
#include<string>
#include<map>
using namespace std;
int main()
{
string ch;
map<int,string> a;
int l = 0;
while(cin>>ch)
{
a[l] = ch;
l++;
}
for(auto it = a.rbegin();it != a.rend();it++)
{
if(it == a.rbegin())
cout<<it->second;
else
cout<<' '<<it->second;
}
system("pause");
return 0;
}