1.题目
中缀表达式求值:
如:(1+2^3!-4)*(5!-(6-(7-(89-0!))))
结果为:2013
2.数据结构与算法
DS:stack
Algorithm:延迟缓冲
代码框架:
使用两个栈,一个数字栈,一个符号栈。
遍历中缀表达式:
是数字就入栈
是字符就判断优先级
1.当前符号>符号栈顶优先级:不计算
2.当前符号<符号栈顶优先级:计算
细节:
符号栈:先push()一个哨兵\0,方便处理边界值
连续多个字符为数字需要特别处理。
单目运算符、双目运算符需要分开处理。
优先级表:逻辑上的二维数组,实质用switch语句进行处理即可。
**符号=**表示遇到了()或\0\0的情况。
遇到():()内部表达式计算完成,符号(弹出,字符串指向下一个位置即可。
遇到\0\0:整个表达式计算完成。
**空字符’ '**表示对于一个合法的中缀表达式,是不可能出现这种情况的,无需考虑。
3.源代码
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int calculate(int n);
int calculate(char top, int left, int right);
char getOrder(char top, char now);
int getNum(string str, int &i);
//中缀表达式求值
int infix_exp(string str){
str += '\0';
stack<int> s1; //数字栈
stack<char> s2; //运算符栈
s2.push('\0');
int len = str.size();
int i = 0;
while(!s2.empty()){
if(isdigit(str[i])){//是数字就入s1 待扩展
/*int re = str[i] - '0';
while(isdigit(str[++i])){
re = re * 10 + (str[i] - '0');
}
s1.push(re);*/
s1.push(getNum(str, i));
}else{//是字符
//获取优先级
char order = getOrder(s2.top(), str[i]);
//根据优先级结果进行处理
switch (order){
case '<': //不计算
s2.push(str[i]);i++;break;
case '>': //计算
if('!' == s2.top()){
int num = s1.top();s1.pop();
s1.push(calculate(num));
}else{
int right = s1.top();s1.pop();
int left = s1.top();s1.pop();
s1.push(calculate(s2.top(), left, right));
}
s2.pop();
break;
case '=':
s2.pop(); i++;break;
}
}
}
return s1.top();
}
//处理连续多个数字
int getNum(string str, int &i){
int re = str[i] - '0';
while(isdigit(str[++i])){
re = re * 10 + (str[i] - '0');
}
return re;
}
//基本单目运算
int calculate(int n){
int multi = 1;
while(n){
multi *= n;
n--;
}
return multi;
}
//基本双目运算
int calculate(char top, int left, int right){
switch (top){
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
case '^': return static_cast<int>(pow(left, right));
}
}
//获取符号优先级
char getOrder(char top, char now){
switch(now){
case '+':
case '-':
return (top=='('||top =='\0')? '<' : '>';
case '*':
case '/':
return (top=='('||top =='\0'||top=='+'||top =='-')? '<' : '>';
case '^':
return (top=='^'||top =='!')? '>' : '<';
case '!':
return (top=='!')? '>' : '<';
case '(':
return '<';
case ')':
return (top=='(')? '=' : '>';
case '\0':
return (top=='\0')? '=' : '>';
}
}
int main()
{
string str = "(1+2^3!-4)*(5!-(6-(7-(89-0!))))";
cout<<"input:\n"<<str<<endl;
cout<<"output:\n"<<infix_exp(str);
return 0;
}
4.时间复杂度
5.结论
当处理较为复杂的问题时。
1.做模拟,弄清整个流程。
2.整合程序框架。
3.再对框架的每个细节分别进行处理。
4.反复调试程序:一般程序写出来99%都会有问题。
先做单模块迭代测试,再做集成测试。
如有错误,请您批评指正。
参考书籍:清华大学《数据结构(C++语言版)》(第三版) 邓俊辉