Text Reverse
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 34466 Accepted Submission(s): 13535
Problem Description
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.
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
3 olleh !dlrow m'I morf .udh I ekil .mca
Sample Output
hello world! I'm from hdu. I like acm.HintRemember to use getchar() to read '\n' after the interger T, then you may use gets() to read a line and process it.
问题链接:HDU1062 Text Reverse。
问题简述:
输入测试例子数量t,然后输入t行字符串,将每一行的每一个单词逆序后输出该行的语句(字符串)。
问题分析:
利用堆栈后进先出的原理,逆序处理可以使用堆栈来实现。每一个单词是用空格或行结束符隔开的。每行的处理到换行符为止。
程序说明:
使用了一个自行实现的堆栈,简单地实现逆序功能。本程序使用getchar()函数处理输入流,除了输入字符压栈外,读入的字符直接输出输出,没有使用多余的缓存。
AC通过的C语言程序如下:
- /* HDU1062 Text Reverse */
-
- #include
-
- #define MAXSTACK 1024
-
- char stack[MAXSTACK];
- int pstack;
-
- void push(char c)
- {
- stack[pstack++] = c;
- }
-
- char pop()
- {
- return stack[--pstack];
- }
-
- int main(void)
- {
- int t;
- char c;
-
- scanf("%d", &t);
- getchar();
- while(t--) {
- pstack = 0;
-
- for(;;) {
- c = getchar();
- if(c == ' ' || c == '\n') {
- while(pstack)
- putchar(pop());
- putchar(c);
- } else
- push(c);
-
- if(c == '\n')
- break;
- }
- }
-
- return 0;
- }
评论记录:
回复评论: