您的位置:首页 > 理论基础 > 数据结构算法

顺序表C++数据结构实验之栈二:一般算术表达式转换成后缀式

2016-08-03 19:19 363 查看

数据结构实验之栈二:一般算术表达式转换成后缀式

Time Limit: 1000MS Memory limit: 65536K

题目描述

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

输入

输入一个算术表达式,以‘#’字符作为结束标志。

输出

输出该表达式转换所得到的后缀式。

示例输入

a*b+(c-d/e)*f#

示例输出

ab*cde/-f*+
#include <iostream>#include <algorithm>#include <cstring>#define sqmax 1010using namespace std;typedef struct{char *base;char *top;int sqsize;} sq;int init(sq &s);void push(sq &s,char n);char pop(sq &s);int empty(sq &s);int main(){char c[260];sq s;int n,m,p,l,i;while(cin>>c!=NULL){init(s);l=strlen(c);for(i=0; i<l; i++){if(c[i]>='a'&&c[i]<='z')cout<<c[i];if(c[i]=='(')push(s,c[i]);if(c[i]==')'){while(*s.top!='('&&!empty(s))cout<<pop(s);pop(s);}if(c[i]=='*'||c[i]=='/'){push(s,c[i]);}if(c[i]=='+'||c[i]=='-'){while(*s.top!='('&&!empty(s))cout<<pop(s);push(s,c[i]);}if(c[i]=='#'){while(!empty(s))cout<<pop(s);break;}}cout<<endl;}}int init(sq &s){s.base=(char *)malloc(sqmax *sizeof(char));if(!s.base) exit(0);s.top=s.base-1;s.sqsize=sqmax;return 1;}void push(sq &s,char n){*++s.top=n;}char pop(sq &s){return *s.top--;}int empty(sq &s){if(s.top==s.base-1)return 1;elsereturn 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  集训 数据结构 c++