中缀转前缀以及前缀表达式的计算!

//例:1 - ( 2 + 3 ) 转换前缀是:- 1 + 2 3
//例:1 + 2 * 3 + ( 4 * 5 + 6 ) * 7 转换前缀是+ + 1 * 2 3 + * 4 5 6 7
//例:1 + ( ( 2 + 3 ) * 4 ) - 5 转换前缀是:- + 1 * + 2 3 4 5 *
//例:123 + ( ( 246 + 39 ) * 48 ) - 55 转换前缀是:- + 123 * + 246 39 48 55

//头文件加起来可绕地球一圈
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;

int MarkLevel(string s)// '('括号问题另外讨论
{
    if(s=="*"||s=="/")return 2;
    else if(s==")")return 0;// 
    else return 1;
}

stack<string>st;
vector<string>pre;
vector<string>mid;

int cal(vector<string>pre)
{
    stack<int>st;
    for(int i=0;i<(int)pre.size();i++)
    {
        if(pre[i][0]>='0'&&pre[i][0]<='9')
        {
            st.push(atoi(pre[i].c_str()));
        }
        else
        {
            int a=st.top();
            st.pop();
            int b=st.top();
            st.pop();
            if(pre[i]=="+")st.push(a+b);
            else if(pre[i]=="-")st.push(a-b);
            else if(pre[i]=="*")st.push(a*b);
            else st.push(a/b);
        }
    }
    return st.top();
}


int main()
{
    freopen("input.txt","r",stdin);
    string s;
    while(cin>>s)
    {
        mid.push_back(s);
    }
    for(int i=(int)mid.size()-1;i>=0;i--)
    {
        if(mid[i][0]>='0'&&mid[i][0]<='9')
        {
            pre.push_back(mid[i]);
        }//是数字直接入队
        else
        {
            if(mid[i]==")")st.push(mid[i]);// 括号问题另外讨论
            else if(mid[i]=="(")
            {
                while(st.top()!=")")
                {
                    pre.push_back(st.top());
                    st.pop();
                }
                st.pop();//弹出(
            }
            else if(st.empty()||(!st.empty()&&MarkLevel(mid[i])>=MarkLevel(st.top())))//其他符号问题
            {
                st.push(mid[i]);
            }
            else
            {
                while((!st.empty()&&MarkLevel(mid[i])<MarkLevel(st.top())))//不空且栈顶元素的等级大于给定元素
                {
                    pre.push_back(st.top());
                    st.pop();
                }
                st.push(mid[i]);
            }
        }//不是数字
    }
    while(!st.empty())
    {
        pre.push_back(st.top());
        st.pop();
    }
    reverse(pre.begin(),pre.end());
    for(int i=0;i<(int)pre.size();i++)
    {
        cout<<pre[i]<<" ";
    }
    reverse(pre.begin(),pre.end());
    printf("%d",cal(pre));
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值