HDU 1062 (stack implementation)

Stacks and stack applications
topic Link: http://acm.hdu.edu.cn/showproblem.php?pid=1062
flip string.

Sample input:
. 3
olleh dlrow!
M'I Morf .udh
the I ekil .mca
Sample Output:
! Hello World
the I'm from HDU.
The I like ACM.

Ideas:
When reading the spaces and rows need to be stored in the stack before the character print it out, did not read spaces and line, which pushed onto the stack.

#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;
}
Published 21 original articles · won praise 41 · views 1037

Guess you like

Origin blog.csdn.net/weixin_45895026/article/details/103949269