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
Sample Input
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))) |
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; }
相关文章推荐
- [Swust OJ 322]--东6宿舍灵异事件(中缀表达式转化为后缀表达式的简单运用)
- swuetoj(表达式转换(0309)
- 数据结构实验之栈与队列二:一般算术表达式转换成后缀式oj
- 数据结构实验之栈与队列二:一般算术表达式转换成后缀式 sdut-oj
- 4.从中缀向后缀转换表达式
- 华师大OJ【1147】进制转换的递归写法
- 中缀到后缀表达式的转换:java-stack实现
- SDUT2132算术表达式转换成后缀式(表达式树)
- SDUT 2132 数据结构实验之栈二:一般算术表达式转换成后缀式
- swust.oj 0964
- swust.oj.319
- 程序判断逻辑问题,蕴含表达式的等价转换
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- [原创]将固定格式时间表达式转换成秒
- 【华为OJ】【096-表达式求值】
- 【算法学习笔记】86.栈 中缀表达式 SJTU OJ 1033 表达式计算
- 栈的运用(中缀表达式转换为后缀表达式,并对后缀表达式求值。)
- 1368 表达式转换
- 中缀表达式转换为前缀表达式
- 【剑指Offer面试编程题】题目1508:把字符串转换成整数--九度OJ