stack计算表达式的值

9.52 使用stack对象处理带圆括号的表达式。遇到左圆括号时,将其标记下来。当你在一个左括号之后遇到右圆括号时,弹出stack对象中这两边括号之间的元素,直到遇到左括号,将左括号也一起弹出栈。 接着在stack对象中压入一个值,用以表明这个用一对圆括号括起来的表达式已经被替换。

程序如下:

#include<iostream>
#include<stack>
#include<string>
using namespace std;

int main()
{
    stack<char> sexp;        //处理表达式的stack对象
    string exp;                //存储表达式的string对象

    //读入表达式
    cout<<"Enter a expression:"<<endl;
    cin>>exp;

    //处理表达式
    string::iterator iter=exp.begin();    //初始迭代器初始位置
    while(iter!=exp.end())
    {
        if(*iter!=')')  //读到的字符不是右圆括号
            sexp.push(*iter);   //标记字符
        else{
            //读到的是右圆括号,弹出元素直到栈顶为左圆括号或栈为空
            while(sexp.top()!='('&&!sexp.empty())
                sexp.pop();
            if(sexp.empty())        //栈为空
            {
                cout<<"parentheses are not matched"<<endl;
                return -1;
            }
            else
            {            //栈顶为左圆括号
                sexp.pop();            //弹出左圆括号
                sexp.push('@');        //表明圆括号的表达式已经被替换
            }
        }
        ++iter;
    }
    if(iter==exp.end())
        cout<<"matched"<<endl;
    return 0;
}

运行结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,可以使用栈来计算表达式。具体步骤如下: 1. 创建一个操作数栈和一个操作符栈。 2. 将表达式字符串转换为字符数组,并遍历每个字符。 3. 如果当前字符是数字,则将它转换为一个操作数,并将其压入操作数栈。 4. 如果当前字符是操作符,则将其压入操作符栈。 5. 如果当前字符是右括号,则弹出操作符栈顶的操作符和操作数栈顶的两个操作数,计算它们的,将结果压入操作数栈。 6. 最后,当表达式遍历完毕后,将操作符栈和操作数栈中的元素依次弹出,按照操作符的优先级计算表达式。 下面是一个示例代码: ```java import java.util.Stack; public class Calculator { public static int calculate(String expression) { Stack<Integer> operandStack = new Stack<>(); Stack<Character> operatorStack = new Stack<>(); char[] tokens = expression.toCharArray(); for (int i = 0; i < tokens.length; i++) { if (Character.isDigit(tokens[i])) { StringBuilder sb = new StringBuilder(); while (i < tokens.length && Character.isDigit(tokens[i])) { sb.append(tokens[i++]); } i--; operandStack.push(Integer.parseInt(sb.toString())); } else if (tokens[i] == '(') { operatorStack.push(tokens[i]); } else if (tokens[i] == ')') { while (operatorStack.peek() != '(') { char operator = operatorStack.pop(); int operand2 = operandStack.pop(); int operand1 = operandStack.pop(); operandStack.push(applyOperator(operator, operand1, operand2)); } operatorStack.pop(); // Pop the left parenthesis. } else if (isOperator(tokens[i])) { while (!operatorStack.isEmpty() && hasPrecedence(tokens[i], operatorStack.peek())) { char operator = operatorStack.pop(); int operand2 = operandStack.pop(); int operand1 = operandStack.pop(); operandStack.push(applyOperator(operator, operand1, operand2)); } operatorStack.push(tokens[i]); } } while (!operatorStack.isEmpty()) { char operator = operatorStack.pop(); int operand2 = operandStack.pop(); int operand1 = operandStack.pop(); operandStack.push(applyOperator(operator, operand1, operand2)); } return operandStack.pop(); } private static boolean isOperator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/'; } private static int applyOperator(char operator, int operand1, int operand2) { switch (operator) { case '+': return operand1 + operand2; case '-': return operand1 - operand2; case '*': return operand1 * operand2; case '/': return operand1 / operand2; default: throw new IllegalArgumentException("Unknown operator: " + operator); } } private static boolean hasPrecedence(char operator1, char operator2) { if (operator2 == '(' || operator2 == ')') { return false; } if ((operator1 == '*' || operator1 == '/') && (operator2 == '+' || operator2 == '-')) { return false; } return true; } } ``` 可以使用以下代码测试: ```java String expression = "2 * (3 + 4) - 5 / 2"; int result = Calculator.calculate(expression); System.out.println(expression + " = " + result); // Output: 2 * (3 + 4) - 5 / 2 = 12 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值