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

一般算术表达式转换成后缀式

2017-08-01 22:52 183 查看

一般算术表达式转换成后缀式

Time Limit: 1000MSMemory Limit: 65536KB[align=center][/align]

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

ab*cde/-f*+
#include<iostream>#include<stdlib.h>const int MaxSize = 100;using namespace std;typedef struct node{char *data;int top;}node;void Init(node &S){S.data = new char[MaxSize];S.top = -1;                  //初始化为-1}bool IsEmpty(node &S){if (S.top == -1)   return true;else return false;}bool IsFull(node &S){if (S.top == MaxSize - 1)  return true;else return false;}void Push(node &S, char ch){if (IsFull(S))   exit(0);else  S.data[++S.top] = ch;               //先++}char Pop(node &S){if (IsEmpty(S))  exit(0);else return S.data[S.top--];           //后--}void CLear(node &S){S.top = 0;}int Pre(char ch){                                        //运算符的比较switch (ch){case'+':case'-':return 2;case '*':case '/':return 3;case'(':case'#':return 1;default:return 0;}}int main(){node S;char ch = '#';Init(S);Push(S, ch);char ch1;while (cin >> ch1&&ch1 != '#'){switch (ch1){case'+':case'-':case'*':case'/':{if (Pre(S.data[S.top]) >= Pre(ch1)){while (Pre(S.data[S.top]) >= Pre(ch1)){cout << Pop(S);}Push(S,ch1);}else Push(S,ch1);break;}case'(':{Push(S,ch1);break;}case')':{char h = Pop(S);while (h != '('){cout << h;h = Pop(S);}break;}default:cout << ch1; break;}}while (S.top != 0)cout << Pop(S);cout << endl;return 0;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构