c++后缀表达式(数据结构与算法分析----C++语言描述)

#include <iostream>
#include<string>
#include <assert.h>
#include<cctype>
#include<stack>

std::string postfix(std::string exp);

int main(){
    std::string infixExp;
    std::cout<<"NOTE: Enter # for infix expression to stop. \n";
    while (true)
    {
        std::cout<<"\nInfix expression? ";
        getline(std::cin,infixExp);
        if (infixExp=="#") break;
        std::cout<<"Postfix expression is "<<postfix(infixExp)<<std::endl;
        
    }
}

std::string postfix(std::string exp){
    char token, topToken;
    std::stack<int> opStack;
    std::string postfixExp;
    const std::string BLANK = " ";
    for (int i = 0; i < exp.length(); i++)
    {
        token = exp[i];
        switch (token)
        {
        case ' ': break;
        case '(': opStack.push(token); break;
        case ')': 
            for (;;)
            {
                assert(!opStack.empty());
                topToken = opStack.top();
                opStack.pop();
                if(topToken == '(') break;
                postfixExp.append(BLANK + topToken);
            }
            break;
        case '+':
        case '-':
        case '*':
        case '/':
        case '%':
            for(;;){
                if (opStack.empty() || 
                opStack.top() == '(' || 
                (token=='*' || token=='/' || token=='%') &&
                (opStack.top() == '+' || opStack.top() == '-'))
                {
                    opStack.push(token);
                    break;
                }
                else
                {
                    topToken = opStack.top();
                    opStack.pop();
                    postfixExp.append(BLANK + topToken);
                }
            }
            break;
        default:
            postfixExp.append(BLANK + token);
            for(;;){
                if(!isalnum(exp[i+1])) break;
                i++;
                token = exp[i];
                postfixExp.append(1,token);
            }
        }
    }
    for(;;){
        if (opStack.empty()) break;
        topToken = opStack.top();
        opStack.pop();
        if (topToken!='(')
        {
            postfixExp.append(BLANK + topToken);
        }
        else
        {
            std::cout<<"*** Error in infix expression ***\n";
            break;
        }
    }

    return postfixExp;

}
    

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值