您的位置:首页 > 其它

swustoj表达式转换(0309)

2017-04-15 22:27 232 查看
给出一个括号算术表达式,表达式中包含:操作符:+、-、*、/、^,并且操作符的优先级依次增高;小写字母a, b, c,…, z;小括号()。算术表达式以中缀形式给出,如(a+b),我们假定表达式中没有出现连续两个以上操作符的情形,比如a*b*c,这种形式会表达成(a*(b*c))或((a*b)*c)。并且算术表达式总是以”(“开始,以“)”结束。请将给定的字条串转换成后缀形式。(见示例输入输出)

Description

T,表达式的个数(T <= 100) 以下T行,每行包括一个表达式,并且算术表达式(算术表达式长度小于200)

Input

输出转换后的字符串,每行一组测试数据

Output

1
2
3
4
5

3
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))

Sample Input

1
2
3
4

abc*+
ab+zx+*
at+bac++cd+^*

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include<stack>
#include<iostream>
#include<string.h>
#include<math.h>
#include<utility>//pair头文件
using namespace std;
struct node
{
char k;
int Second;
}p[7] = { { '(',1 },{ ')',8 },{ '*',5 },{ '/',5 },{ '+',4 },{ '-',4 },{ '^',6 } };
stack<char>q;

bool juge(char a)
{
int ss = -1;
int tt = -1;
for (int j = 0; j < 7; j++)
{
if (a == p[j].k)
{
ss = p[j].Second;
}
if (q.top() == p[j].k)
{
tt = p[j].Second;
}
}
if (ss > tt)//注意是 '>'
{
return true;
}
else
{
return false;
}
}

int main()
{
int t;
cin >> t;
while (t--)
{
char str[1000];
cin >> str;
char ans[1000];
int k = 0;

for (int i = 0; i < strlen(str); i++)
{
if (str[i] >= 'a'&&str[i] <= 'z')
{
cout << str[i];
}
else if (str[i] == '(')
{
q.push(str[i]);
}
else if (str[i] == ')')
{
while (q.top() != '(')
{
cout << q.top();
q.pop();
}
q.pop();
}
else if (q.empty())
{
q.push(str[i]);
}
else if (str[i] == '^')
{
q.push(str[i]);
}
else
{
if (juge(str[i]))
{
q.push(str[i]);
}
else
{
while (!q.empty() && !juge(str[i]))
{
cout << q.top();
q.pop();
}
q.push(str[i]);
}
}
if (i == strlen(str) - 1)
{
while (!q.empty())
{
cout << q.top();
q.pop();
}
}
}
cout << endl;
}
return 0;
}



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