《数据结构》栈的应用——基本计算器

栈的一个经典应用例题就是《基本计算器》,这个算法手写过程我很熟悉,但是代码实现不是很熟手,因此复习阶段有必要把这个算法总结一下。

题目描述,输入一个字符串,包含 数字0-9,(,),+,-,*,/ 以及一些空格,保证输入的数据是合理的,不会出现语义错误,不会出现0作为除数,没有处理开头符号和左括号紧跟负号。

算法实现

#include <iostream>
#include <map>
#include <vector>
#include <stack>
using namespace std;
int cal(vector<string> words, map<char, int> m){
    stack<int> nums;
    stack<char> op;
    for(int i=0;i<words.size();i++){
        char c = words[i][0];
        if(c>='0'&&c<='9'){
            nums.push(stoi(words[i]));
        }
        else if(op.empty()||op.top()=='(')
            op.push(c);
        else{
            while(!op.empty() && m[words[i][0]]<=m[op.top()]){
                // 当前运算符的优先级小于等于符号栈顶运算符的优先级
                if(op.top()=='('&&words[i][0]==')'){ // 碰到了左括号
                    op.pop(); //左括号出栈
                    break;
                }
                int b = nums.top();
                nums.pop();
                int a = nums.top();
                nums.pop();
                switch(op.top()){
                    case '+': a = a+b; break;
                    case '-': a = a-b; break;
                    case '*': a = a*b; break;
                    case '/': a = a/b; break;
                    default:
                        break;
                }
                nums.push(a); //计算之后再入栈
                op.pop();     // 符号出栈
            }
            if(c!=')')       // 如果当前符号是右括号不必入符号栈
                op.push(c); //当前符号入栈
        }
    }
    return nums.top();
}
int main() {
    string input;
    getline(cin, input);
    map<char, int> m; //优先级定义
    m['#'] = 0;
    m['+'] = 1;
    m['-'] = 1;
    m['*'] = 2;
    m['/'] = 2;
    m['('] = 3;
    m[')'] = 0;
    input += '#';

    // 1、词法分析,先把必要的单词分隔开来
    vector<string> words;
    string num;
    for(int i=0;i<input.length();i++){
        num = "";
        while(i<input.length() && input[i]>='0'&&input[i]<='9'){
            num += input[i++];
        }
        if(!num.empty()){
            words.push_back(num);
            i--;
            continue;
        }
        char c = input[i];
        if(c==' ') //空格直接跳过
            continue;
        else{
            string s = "";
            s += c;
            words.push_back(s);
        }

    }
    int ans = cal(words, m);
    cout<<ans<<endl;
    return 0;
}

CCF-CSP题目相关
二十四点

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

int main() {
    int n;
    cin>>n;
    stack<int> nums;
    stack<char> op;
    map<char, int> m;
    m['#'] = 0; //结束符
    m['+'] = 1;
    m['-'] = 1;
    m['x'] = 2;
    m['/'] = 2;

    while(n--){
        string str;
        cin>>str;
        str += '#';
        for(auto c: str){
            if(c>='0'&&c<='9')
                nums.push(c-'0');
            else if(op.empty()) //符号栈为空
                op.push(c);      //符号入栈
            else{ //符号栈不空,则判断当前符号的优先级和栈顶符号的优先级
                while(!op.empty()&&m[op.top()] >= m[c]){
                    //符号栈不为空,且符号栈顶的运算符优先级大于等于当前符号优先级
                    char token = op.top();
                    int b=nums.top();
                    nums.pop();
                    int a=nums.top();
                    nums.pop();
                    switch (token){
                        case '+':
                            a = a+b; break;
                        case '-':
                            a = a-b; break;
                        case 'x':
                            a = a*b; break;
                        case '/':
                            a = a/b; break;
                        default:
                            break;
                    }
                    nums.push(a); //计算后的数再压入栈
                    op.pop();
                }
                op.push(c); //当前符号入栈
            }

        }
        if(nums.top()==24)
            printf("Yes\n");
        else
            printf("No\n");
        nums.pop(); //清空栈
        op.pop();
    }
    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值