求中缀表达式的值

求中缀表达式的值


分享一道经典的栈与队列题目。

#include <iostream>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
const int N = 605;

struct node{
    int x;
    char y;
    node(int a=0,char b=0):x(a),y(b){}
};
queue<node> q;
stack<char> s;
stack<int> p;

bool isoperator(char a){
    if(a=='+' || a=='-' || a=='*' || a=='/')
        return true;
    return false;
}
bool isnum(char a){
    if(a >= '0' && a<= '9')
        return true;
    return false;
}
bool isgreater(char a, char b){
    if((a=='*' || a=='/') && (b=='+' || b=='-'))
       return true;
    return false;
}
void init(){
    while(!q.empty()) q.pop();
    while(!s.empty()) s.pop();
    while(!p.empty()) p.pop();
}

int main(){
    int n;
    cin >> n;
    while(n--){
        init();
        char a[N];
        cin >> a;
        for(int i=0;a[i];++i){
            if(a[i] == '('){
                s.push(a[i]);
            }
            else if(a[i] == ')'){
                while(!s.empty()){
                    char c = s.top();
                    s.pop();
                    if(c == '(') break;
                    else q.push(node(0,c));
                }
            }
            else if(isoperator(a[i])){
                while(!s.empty()&&s.top()!='('&&!isgreater(a[i],s.top())){
                    char c = s.top();
                    s.pop();
                    q.push(node(0,c));
                }
                s.push(a[i]);
            }
            else if(isnum(a[i])){
                int t = atoi(a+i);
                while(a[i] && isnum(a[i])){ // in case the end
                    i++;
                }
                i--;
                q.push(node(t));
            }
        }
        while(!s.empty()){
            q.push(node(0,s.top()));
            s.pop();
        }
        while(!q.empty()){
            node t = q.front();
            q.pop();
            if(t.y){
                int t2 = p.top();p.pop();
                int t1 = p.top();p.pop();
                int tmp=0;
                switch (t.y) {
                    case '+':tmp=t1+t2;break;
                    case '-':tmp=t1-t2;break;
                    case '*':tmp=t1*t2;break;
                    case '/':tmp=t1/t2;break;
                    default : break;
                }
                p.push(tmp);
            }
            else{
                p.push(t.x);
            }
        }
        cout << p.top() << endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于中缀表达式程序的代码示例: ```python # 定义运算符的优先级 precedence = {'+': 1, '-': 1, '*': 2, '/': 2} # 定义类 class Stack: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] # 定义中缀表达式函数 def evaluate(expression): # 将表达式转换为仅包含数字、运算符和括号的列表 tokens = [] number = '' for char in expression: if char.isdigit() or char == '.': number += char else: if number: tokens.append(float(number)) number = '' if char != ' ': tokens.append(char) if number: tokens.append(float(number)) # 定义和输出列表 stack = Stack() output = [] # 遍历表达式的每个token for token in tokens: if isinstance(token, float): # 如果是数字,直接输出 output.append(token) elif token in precedence: # 如果是运算符,弹出中优先级较高的运算符,并输出到输出列表中 while not stack.is_empty() and stack.peek() in precedence and precedence[stack.peek()] >= precedence[token]: output.append(stack.pop()) stack.push(token) elif token == '(': # 如果是左括号,将其压入中 stack.push(token) elif token == ')': # 如果是右括号,弹出中左括号前的所有运算符,并输出到输出列表中 while not stack.is_empty() and stack.peek() != '(': output.append(stack.pop()) stack.pop() # 将中剩余的所有运算符弹出并输出到输出列表中 while not stack.is_empty(): output.append(stack.pop()) # 计算输出列表中的后缀表达式 stack = Stack() for token in output: if isinstance(token, float): stack.push(token) else: operand2 = stack.pop() operand1 = stack.pop() if token == '+': stack.push(operand1 + operand2) elif token == '-': stack.push(operand1 - operand2) elif token == '*': stack.push(operand1 * operand2) elif token == '/': stack.push(operand1 / operand2) # 返回计算结果 return stack.pop() ``` 希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值