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

问题:给出一个表达式,含有括号,将其转化成后缀表达式输出

算法:用栈维护将要输出的运算符(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

  1. 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

  2. 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.

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

  4. The operands will be one digit numerals.

  5. 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.

  6. 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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值