栈和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;
}