写了一个简单的表达式计算,为了方便起见,仅仅考虑表达式正确的情况,没有对表达式进行检查。
使用了两个栈:数据栈和符号栈
具体算法见代码:
// datastructure.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include<stack>
#include<string>
using namespace std;
/*calculate expression*/
/* algorithm:
two main struture:
number stack, sign stack
for each number, push into number stack
for each sign:
1) '(': push into sign stack;
2)'+','-','*','/':first compare the priority of current sign.
if is lower than sign stack top value:
---pop two number from number stack
---pop one sign from sign stack
---calculate
---push result into number stack
---push current sign into sign stack
3) ')':
---pop two number
---pop one sign
--- calculate
--- push result into number
---continue until meet the '(';
*/
bool isnumber(char tmp)
{
if(tmp >='0' && tmp <= '9')
return true;
else
return false;
}
int level(char tmp)
{
switch (tmp)
{
case '(':
return 0;
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
}
}
double cal(double a, double b, char sign)
{
switch (sign)
{
case '+':
return (b+a);
case '-':
return (b-a);
case '*':
return b*a;
case '/':
return b/a;
}
}
double calculate(string expression)
{
stack<char> signstack;
stack<double> numberstack;
int i;
i = 0;
while(i < expression.size())
{
char tmp = expression[i];
if(isnumber(tmp))
{
// calculate tmp maybe several char
double tmpnum = 0;
while(isnumber(tmp))
{
tmpnum = tmpnum*10+ (tmp-'0');
i++;
if(i<expression.size())
tmp = expression[i];
else
break;
}
numberstack.push(tmpnum);
}
else
{
if(tmp == '('|| signstack.empty())
signstack.push(tmp);
else if(tmp == ')')
{
char tmpsign = signstack.top();
while(!signstack.empty() && signstack.top()!='(')
{
tmpsign = signstack.top();
double tmpnum1 = numberstack.top();
numberstack.pop();
double tmpnum2 = numberstack.top();
numberstack.pop();
double tmpnum3 = cal(tmpnum1,tmpnum2,signstack.top());
signstack.pop();
numberstack.push(tmpnum3);
}
signstack.pop();
}
else if(level(tmp) < level(signstack.top()))
{
double tmpnum1 = numberstack.top();
numberstack.pop();
double tmpnum2 = numberstack.top();
numberstack.pop();
double tmpnum3 = cal(tmpnum1,tmpnum2,signstack.top());
signstack.pop();
signstack.push(tmp);
numberstack.push(tmpnum3);
}
else if(level(tmp) >= level(signstack.top()))
{
signstack.push(tmp);
}
i++;
}
}
while(!signstack.empty()&&!numberstack.empty())
{
double tmpnum1 = numberstack.top();
numberstack.pop();
double tmpnum2 = numberstack.top();
numberstack.pop();
double tmpnum3 = cal(tmpnum1,tmpnum2,signstack.top());
signstack.pop();
numberstack.push(tmpnum3);
}
return numberstack.top();
}
int main()
{
string expression = "(1+2*(3-4*(5+1)))/8+1";
double r = calculate(expression);
cout << "result for " << expression<<" is: " << r << endl;
system("pause");
return 0;
}