堆栈 - 在C中评估Postfix表达式

时间:2016-04-22 23:57:21

标签: c stack postfix-notation

我的任务是实现int isOperator(char *); 操作数得到推动,操作员获得顶部,弹出,表达式被推送。

  Example:
  6 5 2 3.14 + 8 * + 3 + *
  Pushing: 6.000000  
  Pushing: 5.000000
  Pushing: 2.000000
  Pushing: 3.140000
  Pushing: 2.000000+3.140000=5.140000

我的实施有问题吗? 这是我的intOperator(char *)。

int isOperator(char *s){

int i;
char Ops[] = { '+', '-', '*', '/' };

for (i = 0; i < 4; i++)
{
    if (s == Ops[i])
        return (1);
    return (0);
}
}

这是我推送和弹出操作数和运算符的实现。

    S = CreateStack();
n = sizeof(postfixExpression) / sizeof(postfixExpression[0]); // Compute array size
for (i = 0; i<n; i++){ // Print elements of postfix expressions
    printf("%s ", postfixExpression[i]);
}
printf("\n");

for (i = 0; i<n; i++){

    if (isalnum(postfixExpression[i])){
        Push(atof(postfixExpression[i]), S);
        printf("Pushing: %d", atof(postfixExpression[i]));
    }
    else if (isOperator(postfixExpression[i]))
    {
        rightOperand = Top(S);
        Pop(Top(S));
        leftOperand = Top(S);
        Pop(Top(S));

        switch (isOperator(postfixExpression[i])){
        case '+':
            Push(leftOperand + rightOperand, S);
            printf("Pushing: %d+%d=%d", leftOperand, rightOperand, leftOperand + rightOperand);
            break;
        case '-':
            Push(leftOperand - rightOperand, S);
            printf("Pushing: %d-%d=%d", leftOperand, rightOperand, leftOperand - rightOperand);
            break;
        case '*':
            Push(leftOperand * rightOperand, S);
            printf("Pushing: %d*%d=%d", leftOperand, rightOperand, leftOperand * rightOperand);
            break;
        case '/':
            Push(leftOperand / rightOperand, S);
            printf("Pushing: %d/%d=%d", leftOperand, rightOperand, leftOperand / rightOperand);
            break;
        default:
            break;
        }

    }
    else
        break;
}

printf("%s\n", S);
DisposeStack(S);
return 0;

1 个答案:

答案 0 :(得分:1)

这是一个更简单的实现:

int isOperator(char *s)
{
    return strchr("+-*/", s[0]) && s[1] == '\0';
}

如果s中的第一个字符是运算符而第二个字符是空终止符(表示运算符字符后面没有其他内容,用于严格检查),则返回1(true)。

对于堆栈逻辑,弹出时应确保堆栈不为空。