链接:https://vjudge.net/problem/HDU-1062

Task

Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow. Each test case contains a single line with several words. There will be at most 1000 characters in a line.

Output

For each test case, you should output the text which is processed.

Sample

input:

1
2
3
4
3
olleh !dlrow
m'I morf .udh
I ekil .mca

output:

1
2
3
hello world!
I'm from hdu.
I like acm.

Solution

将一句话中被空格分开的字符串们反序,用栈。未读到空格或换行或结束符时,向栈中压入字符。读到空格或换行或结束符时一次性弹出栈中所有字符,特别地,读到换行或结束符时跳出一次循环。 注意输入每一行时用getchar()等待输入,否则会乱

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<cstdio>
#include<stack>
using namespace std;
const int MAX=1000;
int main(){
  int n;
  // get n
  while(scanf("%d",&n)!=EOF){
    // wait for input
    getchar();
    // each line
    while(n--){
      stack<char> sta;
      // each char
      while(1){
        char cur=getchar();
        if(cur==' '||cur=='\n'||cur==EOF){
          while(!sta.empty()){printf("%c",sta.top()); sta.pop();}
          if(cur=='\n'||cur==EOF) break;
          printf(" ");
        }
        else{
          sta.push(cur);
        }
      }
      printf("\n");
    }
  }
  return 0;
}