c - 堆栈 - 计算 C 中的后缀表达式

标签 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;

最佳答案

一个更简单的实现是这样的:

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

如果 s 中的第一个字符是运算符,第二个字符是空终止符(为了严格检查,这意味着运算符字符后面没有其他内容),则返回 1 (true)。

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

关于c - 堆栈 - 计算 C 中的后缀表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805003/

相关文章:

c++ - 为什么不总是在堆栈上实例化对象? C++

c - 将函数参数加载到堆栈上,然后在 C 中运行该函数

c++ - 后修复计算器,返回错误值

character - 当中缀表示法中的数字已知时,后缀表示法中的字符数

java - 调车场算法解析函数参数

c++ - 名称或类型具有某种语言链接意味着什么?

c - MIPS 上的 Valgrind 报告没有堆使用

c - 为什么函数堆栈帧中的参数、变量和帧指针之间存在间隙?

c - 二叉树的层序遍历

c - 在 glibc 上覆盖 pthread 函数但在 musl 上不覆盖时出现神秘的段错误