Text Reverse


STL stack
#include<bits/stdc++.h>
using namespace std;
int main(){
int n; scanf("%d",&n); getchar(); //EOF:文件结束
while(n--){
stack<char> s;
while(true){
char ch = getchar(); //一次读入一个字符
if(ch==' '||ch=='\n'||ch==EOF){ //EOF:文件结束 
//三个条件满足一个就全部输出(输出并清除栈顶) 
while(!s.empty()){ printf("%c",s.top()); s.pop();}
}
else s.push(ch); //入栈
}
printf("\n");
}
return 0;
}

笔记:栈和队列不同,队列是“先进先出”,栈是“先进后出”,STL stack是栈的模板

手写栈
#include<bits/stdc++.h>
const int N = 100100;
struct mystack{
char a[N];                            //存放栈元素,字符型
  int t = 0;                            //栈顶位置
  void push(char x){ a[++t] = x; }      //送入栈
  char top()       { return a[t]; }     //返回栈顶元素
  void pop()       { t--;         }     //弹出栈顶
  int empty()      { return t==0?1:0;}  //返回1表示空
}st;
int main(){
int n; scanf("%d",&n);  getchar();
while(n--){
  while(true){
    char ch = getchar();            //一次读入一个字符
    if(ch==' '||ch=='\n'||ch==EOF){
while(!st.empty()){ printf("%c",st.top()); st.pop();}  //输出并清除栈顶
      if(ch=='\n'||ch==EOF)  break;
printf(" ");
}
else    st.push(ch);              //入栈
}
printf("\n");
}
return 0;
}

注意:手写栈虽然麻烦一些,但是比直接调用STL stack模板少了一些不用的沉余代码

警告:

单元信息
513 F:\program_code\Text-Reverse.cpp[Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11
转载:弹出警告解决方案
版权声明:

本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_17808131/article/details/119782760

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注