您的位置:首页 > 其它

中缀表达式转换为后缀表达式

2016-11-23 18:13 549 查看
问题:给出一个表达式,含有括号,将其转化成后缀表达式输出

算法:用栈维护将要输出的运算符(operator)

读入一个token

1)如果是数,直接输出

2)如果是运算符(不含括号),比较其与栈顶元素优先级

若栈顶元素同级或更高级,则将其出栈并输出,直到栈为空或者栈顶运算符级别更低

3)如果是左括号'(', 则将其入栈

4)如果是右括号')', 则将栈顶元素依次出栈并输出,直到有匹配的‘('

最后遇到的’('出栈不输出

当所有读入完成,将栈顶元素依次出栈输出

这里有几个例子。

例题:UVa 727 Equation

Write a program that changes an infix expression to a postfix expression according to the followingspecifications.

Input

The infix expression to be converted is in the input file in the format of one character per line,with a maximum of 50 lines in the file. For example, (3+2)*5 would be in the form:

(3+2)*5

The input starts with an integer on a line by itself indicating the number of test cases. Severalinfix expressions follows, preceded by a blank line.

The program will only be designed to handle the binary operators
+,
-,
*,
/.

The operands will be one digit numerals.

The operators *
and /
have the highest priority. The operators
+
and -
have the lowest priority.Operators at the same precedence level associate from left to right. Parentheses act as groupingsymbols that over-ride the operator priorities.

Each testcase will be an expression with valid syntax.

Output

The output file will have each postfix expression all on one line. Print a blank line between differentexpressions.

Sample Input

1

(

3

+

2

)

*

5

Sample Output

32+5* 

/*
PROG: UVa727
*/

#include <cstdio>
#include <cstring>
#include <cctype>
#include <vector>
using namespace std;

#define MAXN 100
char s[MAXN], sp;

#define DEBUG 1
#define LOG(...) do { if (DEBUG) fprintf(stderr, __VA_ARGS__); } while(0)

int main(void) {
int Z; scanf("%d", &Z);
getchar(); getchar();
for (int z = 0; z < Z; ++z) {
if (z) printf("\n");
sp = 0;
int cnt = 0;
while (1) {
++cnt;
if (cnt > 100) break;
int ch = getchar();
// LOG("%c ", ch);
if (ch != '\n' && ch != EOF) {
getchar();
if (isdigit(ch)) putchar(ch);
else switch (ch) {
case '(': s[sp++] = ch; break;
case '+': case '-':
while (sp && s[sp-1]!='(') putchar(s[--sp]);
s[sp++] = ch;
break;
case '*': case '/':
while (sp && (s[sp-1]=='*'||s[sp-1]=='/')) putchar(s[--sp]);
s[sp++] = ch;
break;
case ')':
while (sp && s[sp-1]!='(') putchar(s[--sp]);
--sp;
break;
}
}
else {
while (sp) putchar(s[--sp]);
putchar('\n');
break;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: