全部评论 3

  • https://sso.xiaomawang.com/login.html?loginMethods=password_sms&loginSuccessCallback=https%3A%2F%2Fonline.xiaomawang.com%2FlearnCenter%2F%3Fislogin%3D1&xmAppId=xmw6730975576313&skipPwdSet=true&theme=online#/login

    1周前 来自 广东

    0
  • 后缀求值:
    使用栈去存储操作数
    正序扫描字符串
    遇到数字就压入栈中
    遇到运算符就拿出两个栈顶
    因为是左算右
    所以第二个栈顶是左,第一个是右
    前缀求值:
    使用栈去存储操作数
    逆序扫描字符串
    遇到数字就压入栈中
    遇到运算符拿出两个栈顶
    此时第一个栈顶是左,第二个是右
    
    中缀求值:边转后缀边求解
    

    1周前 来自 广东

    0
  • #include<bits/stdc++.h>
    using namespace std;
    
    stack<int> num;
    stack<char> op;
    int level(char op) {
    	if (op == '+' || op == '-')
    		return 0; //+或-的优先级比较低
    	return 1;
    }
    void calc() {
    	int r = num.top(); num.pop();//栈顶是右操作数
    	int l = num.top(); num.pop();//次栈顶是左操作数
    	if (op.top() == '+') num.push(l + r);
    	if (op.top() == '-') num.push(l - r);
    	if (op.top() == '/') num.push(l / r);
    	if (op.top() == '*') num.push(l * r);
    	op.pop();//弹出运算符
    }
    int main() {
    	string s;
    	cin >> s;
    	for (int i = 0; i < s.length(); i++) {
    		if (s[i] >= '0' && s[i] <= '9') {
    			num.push(s[i] - '0');
    		}
    		else {
    			if (s[i] == '(') {
    				op.push(s[i]);//左括号直接进栈
    			}
    			else if (s[i] == '+'||s[i]=='-'||s[i]=='*'||s[i]=='/') {
    				while (op.size() && op.top()!='('&&level(op.top()) >= level(s[i])) {
    					calc();
    				}
    				op.push(s[i]);
    			}
    			else if (s[i] == ')') {
    				while (op.top() != '(') {
    					calc();
    				}
    				op.pop();//弹出左括号
    			}
    		}
    	}
    	while (op.size()) {
    		calc();
    	}
    	cout << num.top();
    	return 0;
    }
    

    1周前 来自 广东

    0

热门讨论