题目:输入一个中缀表达式的字符串,出去表达式的结果(只考虑整数)。
主要思路为先用栈把中缀表达式转换为后缀表达式,然后计算后缀表达式的值。
1 char * InfixToPostfix(char *s) { 2 if (s == NULL) return NULL; 3 stack<char> st; 4 stack<char> post; 5 6 char *p = s; 7 int priority[256] = {0}; //设置运算符优先级 8 priority[‘+‘] = 0; 9 priority[‘-‘] = 0; 10 priority[‘*‘] = 1; 11 priority[‘/‘] = 1; 12 priority[‘(‘] = -1; 13 14 15 while (*p != ‘\0‘) { 16 if (*p >= ‘0‘ && *p <= ‘9‘) { 17 post.push(*p++); 18 } else if (*p == ‘(‘) { 19 st.push(*p++); 20 } else if (*p == ‘)‘) { 21 while (!st.empty() && st.top() != ‘(‘) { 22 post.push(st.top()); 23 st.pop(); 24 } 25 st.pop(); //‘(’出栈 26 ++p; 27 } else { 28 while (!st.empty() && priority[st.top()] >= priority[*p]) { 29 post.push(st.top()); 30 st.pop(); 31 } 32 st.push(*p++); 33 } 34 } 35 36 while (!st.empty()) { 37 post.push(st.top()); 38 st.pop(); 39 } 40 41 while (!post.empty()) { 42 st.push(post.top()); 43 post.pop(); 44 } 45 46 int len = strlen(s); 47 char *res = new char[len + 1]; 48 int i = 0; 49 while (!st.empty()) { 50 res[i++] = st.top(); 51 st.pop(); 52 } 53 res[i] = ‘\0‘; 54 55 return res; 56 } 57 58 int BinaryComp(int a, int b, char c) { 59 switch (c) { 60 case ‘*‘: 61 return a * b; 62 break; 63 case ‘+‘: 64 return a + b; 65 break; 66 case ‘-‘: 67 return a - b; 68 break; 69 case ‘/‘: 70 return a /b; 71 break; 72 default: 73 break; 74 } 75 } 76 77 int CalCul(char *s) { 78 if (s == NULL) 79 return 0; 80 stack<int> st; 81 while (*s != ‘\0‘) { 82 if (*s >= ‘0‘ && *s <=‘9‘) { 83 st.push(*s - ‘0‘); 84 ++s; 85 } else { 86 int a = st.top(); 87 st.pop(); 88 int b = st.top(); 89 st.pop(); 90 int res = BinaryComp(a, b, *s); 91 s++; 92 st.push(res); 93 } 94 } 95 96 return st.top(); 97 }
原文:http://www.cnblogs.com/vincently/p/4358274.html