算术表达式的转换
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。
因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。
Input
输入一算术表达式,以\'#\'字符作为结束标志。(数据保证无空格,只有一组输入)
Output
输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。
Sample Input
a*b+(c-d/e)*f#
Sample Output
+*ab*-c/def a*b+c-d/e*f ab*cde/-f*+
提示:本题和之前的求后缀式相同,就是多出了求前缀式和中缀式,所以只要明白其原理就可类比做出这道题。
代码实现如下(g++):
#include <bits/stdc++.h> using namespace std; char str[100], string1[100]; stack<char >S1; stack<char >S2; stack<char >S3; void Pre(char str[]); void In(char str[]); void Post(char str[]); int main() { scanf("%s", str); Pre(str); In(str); Post(str); return 0; } void Pre(char str[])//前缀表达式 { for(int i = strlen(str)-2; i >= 0; i--) { char x = str[i]; if(x >= 'a' && x <= 'z') { S3.push(x); } else { if(x == ')' || S2.empty() ) { S2.push(x); } else if(x == '(') { while(S2.top() != ')') { S3.push(S2.top()); S2.pop(); } S2.pop(); } else if(x == '*' || x == '/') { S2.push(x); } else if(x == '+' || x == '-') { if(S2.top() == x) { S2.push(x); } else { while(!S2.empty() && S2.top() != ')') { if(S2.top() == '*' || S2.top() == '/') { S3.push(S2.top()); S2.pop(); } else { break; } } S2.push(x); } } } } while(!S2.empty()) { S3.push(S2.top()); S2.pop(); } while(!S3.empty()) { cout << S3.top(); S3.pop(); } cout << endl; } void In(char str[])//中缀表达式 { for(int i = 0; str[i] != '#'; i++) { if(str[i] != '(' && str[i] != ')') { cout << str[i]; } } cout << endl; } void Post(char str[])//后缀表达式 { for(int i = 0; str[i] != '#'; i++) { char x = str[i]; if(x >= 'a' && x <= 'z') { cout << x; } else { if(x == '(' || S1.empty()) { S1.push(x); } else if(x == ')') { while(S1.top() != '(') { cout << S1.top(); S1.pop(); } S1.pop(); } else if(x == '+' || x == '-') { while(!S1.empty() && S1.top() != '(') { cout << S1.top(); S1.pop(); } S1.push(x); } else if(x == '*' || x == '/') { while(!S1.empty() && S1.top() != '(') { if(S1.top() == '*' || S1.top() == '/') { cout << S1.top(); S1.pop(); } else { break; } } S1.push(x); } } } while(!S1.empty()) { cout << S1.top(); S1.pop(); } cout << endl; } /*************************************************** Result: Accepted Take time: 0ms Take Memory: 160KB ****************************************************/