问题
by now I just finish the expression turning to postfix expression, and I try to evaluate but something goes wrong and confusing me long time, and I just know how to fix it.
This is my code turn to postfix expression:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define MAXBUFFER 10
#define OK 1
#define ERROR 0
typedef char ElemType;
typedef int Status;
typedef struct {
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
Status InitStack(sqStack *s) {
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if ( !s->base ) {
exit(0);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
return OK;
}
Status Push(sqStack *s, ElemType e) {
//if the stack is full
if ( s->top - s->base >= s->stackSize ) {
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if ( !s->base ) {
exit(0);
}
s->top = s->base + s->stackSize;
s->stackSize += STACKINCREMENT;
}
//store data
*(s->top) = e;
s->top++;
return OK;
}
Status Pop(sqStack *s, ElemType *e) {
if ( s->top == s->base ) {
return ERROR;
}
*e = *--(s->top);
return OK;
}
int StackLen(sqStack s) {
return (s.top - s.base);
}
int main() {
sqStack s;
char c;
char e;
InitStack(&s);
printf("Please input your calculate expression(# to quit):\n");
scanf("%c", &c);
while ( c != '#' ) {
while ( c >= '0' && c <= '9' ) {
printf("%c", c);
scanf("%c", &c);
if ( c < '0' || c > '9' ) {
printf(" ");
}
}
if ( ')' == c ) {
Pop(&s, &e);
while ( '(' != e ) {
printf("%c ", e);
Pop(&s, &e);
}
} else if ( '+' == c || '-' == c ) {
if ( !StackLen(s) ) {
Push(&s, c);
} else {
do {
Pop(&s, &e);
if ( '(' == e ) {
Push(&s, e);
} else {
printf("%c", e);
}
}while ( StackLen(s) && '(' != e );
Push(&s, c);
}
} else if ( '*' == c || '/' == c || '(' == c ) {
Push(&s, c);
} else if ( '#' == c ) {
break;
} else {
printf("\nInput format error!\n");
return -1;
}
scanf("%c", &c);
}
while ( StackLen(s) ) {
Pop(&s, &e);
printf("%c ", e);
}
return 0;
}
When I put 3*(7-2)# it returns 3 7 2 -
Things go right, but I don't know how to do evaluate it next, I just turn it to postfix expression and I want to evaluate it using stack.
回答1:
You have not taken care of operator precedence at all while converting to polish notation. Its difficult to give full code but this is how i did it assuming we build a string along strBuild.
Converting to RPN
if (token is integer)
{
strBuild.Append(token);
strBuild.Append(" ");
}
else if (token is Operator)
{
while (isOperator(Stack.Peek()))
{
if (GetExprPrecedence(token) <= GetExprPrecedence(Stack.Peek()))
{
strBuild.Append(Stack.Pop());
strBuild.Append(" ");
}
else
break;
}
Stack.Push(token);
}
else if (token == '(')
{
Stack.Push(token);
}
else if (token == ')')
{
while (Stack.Peek() != '(')
{
if (Stack.Count > 0)
{
strBuild.Append(Stack.Pop());
strBuild.Append(" ");
}
else
{
Show("Syntax Error while Parsing");
break;
}
}
Stack.Pop();
}
while (Stack.Count > 0 && isOperator(Stack.Peek()))
{
if (Stack.Peek() == '(' || Stack.Peek() == ')')
{
MessageBox.Show("All Tokens Read - Syntax Error");
break;
}
Stack.Pop();
}
return strBuild;
strBuild should be the RPN string. Now to evaluate.
Evaluate
for (int i = 0; i < StrPostFix.Length; i++)
{
token = StrPostFix[i];
if (isOperator(token))
{
switch (token)
{
case "/":
op2 = Stack.Pop();
op1 = Stack.Pop();
val = op1 / op2;
break;
case "*":
op2 = Stack.Pop();
op1 = Stack.Pop();
val = op1 * op2;
break;
case "+":
op2 = Stack.Pop();
op1 = Stack.Pop();
val = op1 + op2;
break;
case "-":
op2 = Stack.Pop();
op1 = Stack.Pop();
val = op1 - op2;
break;
}
Stack.Push(val);
}
else
Stack.Push(token);
}
return Stack.Pop();
return Stack.Pop(); pops the evaluated value and returns. Now for your main doubt which i did not answer since you have not taken care of it, this is how you can handle precedence issue:
enum OperatorPrecedence { Add, Minus, Mult, Div, Brackets };
int GetExprPrecedence(string op)
{
int p = 0;
switch (op)
{
case "(":
p = (int)OperatorPrecedence .Brackets;
break;
case "/":
p = (int)OperatorPrecedence .Div;
break;
case "*":
p = (int)OperatorPrecedence .Mult;
break;
case "-":
p = (int)OperatorPrecedence .Minus;
break;
case "+":
p = (int)OperatorPrecedence .Add;
break;
}
return p;
}
Note the pseudo-code resembles C-Sharp since that is what i work on. I have tried my best to make it look algorithmic and also not vague so that you can relate to your code. Result by my Algorithm:
Note i use Box Brackets [ instead of Round (for my expressions. Final Answer was 15.
来源:https://stackoverflow.com/questions/19443251/how-to-evaluate-arithmetic-expression-using-stack-c