1. 程式人生 > >HDU1062 Text Reverse【水題】

HDU1062 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.

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. Hint
Remember to use getchar() to read '\n' after the interger T, then you may use gets() to read a line and process it.

問題簡述

  輸入測試例子數量t,然後輸入t行字串,將每一行的每一個單詞逆序後輸出該行的語句(字串)。

問題分析

  利用堆疊後進先出的原理,逆序處理可以使用堆疊來實現。每一個單詞是用空格或行結束符隔開的。每行的處理到換行符為止。

程式說明

  使用了一個自行實現的堆疊,簡單地實現逆序功能。本程式使用getchar()函式處理輸入流,除了輸入字元壓棧外,讀入的字元直接輸出輸出,沒有使用多餘的快取。

AC通過的C語言程式如下:

/* HDU1062 Text Reverse */

#include <stdio.h>

#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;
}