HDU-1062,Text Reverse(字符串处理 and 栈)

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. 

解题思路: 

看到题目,相信大家应该知道这道题就是字符串逆置,我们可以考虑将其存入栈中,然后依次输出就可以了,题目的要求是完全符合栈的“先进后出,后进先出”的特点的。剩下的我们看代码↓↓↓ 

程序代码: 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
int main()
{
	int n;
	char ch;
	scanf("%d",&n);
	getchar();//吸收回车符 
	while(n--)
	{
		stack<char> s;//定义一个栈 
		while(1)
		{
			ch=getchar();//每次读入一个字符 
			if(ch==' '||ch=='\n'||ch==EOF)//三个特殊的字符 
			{
				while(!s.empty())//栈不为空 
				{
					printf("%c",s.top());//输出此时的栈顶元素 
					s.pop();//清除栈顶元素 
				}
				if(ch=='\n'||ch==EOF)//结束条件 
					break;
				printf(" ");//记得每个单词(除了最后一个)后面都有一个空格 
			}
			else
				s.push(ch);//将这个字符压入栈 
		}
		printf("\n");
	}
	return 0;
}
发布了274 篇原创文章 · 获赞 282 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43823808/article/details/104061194