HDU 1062(栈实现)

栈和stack应用
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1062
翻转字符串。

样例输入:
3
olleh !dlrow
m’I morf .udh
I ekil .mca
样例输出:
hello world!
I’m from hdu.
I like acm.

思路:
当读取到空格和换行时,需将其之前存入栈的字符打印出来,未读取到空格和换行时,将其压入栈中。

#include<bits/stdc++.h>  
#include<stack>
using namespace std;
int main(){
	 int n;
	 char ch;
	 cin>>n;
	 getchar();
	 while(n--){
	  	stack<char>s;		//定义栈
	 	 while(1){
	  	 ch=getchar();		//一次读入一个字符
	   	 if(ch == ' '||ch =='\n'){
	   	 while(!s.empty()){	//检查栈是否为空
	     		cout<<s.top(); //输出栈顶;
	    		 s.pop();  //清除栈顶; 出栈是必须进行两步操作,先top再pop
	   	 }
	    	if(ch=='\n')
	   	 break;
	   	 cout<<" "; 
	  }
	   else
	    s.push(ch);   //放入栈顶; 
	  }
	  cout<<endl; 
 	}
	 return 0;
}
发布了21 篇原创文章 · 获赞 41 · 访问量 1037

猜你喜欢

转载自blog.csdn.net/weixin_45895026/article/details/103949269