中缀表达式转后缀表达式求值

本文介绍了一个C++程序实现,该程序能够将输入的中缀表达式转换为后缀表达式,并计算其值。涉及的操作包括加、减、乘、除以及括号的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

笔试出这道题出了好几次了, 总是写不好,还是得好好准备啊。参考百度百科,但是那里不是写的太好,改进了一些, 并没有改完。等有时间再改改。

// Test0.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <queue>
#include <exception>
#include <cmath>
#include <stack>
#include <algorithm>
#include <vector>
#include <windows.h>

using namespace std;

//判断是否为操作符
bool isOper(char c)
{
    if ( (c == '+') || (c == '-') || (c == '*') || ( c == '/') || ( c == '(') || ( c == ')'))
        return true;
    
    if( c >= '0' && c <= '9')
        return false;
    else
    {
        cout<<"Operator flag is illogic."<<endl;
        Sleep(3000);
        exit(-1);
    }
}

//判断操作符的优先级
//top_op为栈顶操作符
//InfixExp_op为当前读入操作符
//如果栈顶操作符优先级高,则弹出栈顶操作符
//如果栈顶操作符优先级低,则压入当前读入操作符
bool isHigh(char top_op,char InfixExp_op)
{
    if ((top_op == '+') && (InfixExp_op == '+')) return true;
    if ((top_op == '+') && (InfixExp_op == '-')) return true;
    if ((top_op == '-') && (InfixExp_op == '+')) return true;
    if ((top_op == '-') && (InfixExp_op==  '-')) return true;
    if ((top_op == '*') && (InfixExp_op == '+')) return true;
    if ((top_op == '*') && (InfixExp_op == '-')) return true;
    if ((top_op == '*') && (InfixExp_op == '*')) return true;
    if ((top_op == '*') && (InfixExp_op == '/')) return true;
    if ((top_op == '/') && (InfixExp_op == '+')) return true;
    if ((top_op == '/') && (InfixExp_op == '-')) return true;
    if ((top_op == '/') && (InfixExp_op == '*')) return true;
    if ((top_op == '/') && (InfixExp_op == '/')) return true;
    if (InfixExp_op == ')') return true;
    return false;
}


void input(vector <char> *InfixExp)
{
    string str;

    cin>>str;
    string::iterator iter = str.begin();
    
    while(iter != str.end())
    {
        (*InfixExp).push_back(*iter++);
    }

}

void output(vector <char> *postfixExp)
{
    vector<char>::iterator postfixExp_it;

    for(postfixExp_it = postfixExp->begin(); postfixExp_it != postfixExp->end(); postfixExp_it++)
        cout << *postfixExp_it << " ";

    cout <<endl;
}

//不输出括号
//如果表达式中括号不配对
//则可能有多余的括号未弹出
void output2(vector <char> *postfixExp)
{
    vector <char> ::iterator postfixExp_it;//后缀表达式迭代器
    for(postfixExp_it=postfixExp-> begin();postfixExp_it!=postfixExp-> end();postfixExp_it++)
    {
        if ((*postfixExp_it!= '( ')&&(*postfixExp_it!= ') '))
            cout <<*postfixExp_it << " ";
    }
    cout <<endl;
}

//中缀表达式转后缀表达式
void InfixToPostfix(vector<char> *InfixExp, vector<char> *postfixExp)
{    
    stack<char> mystack;
    vector<char> ::iterator InfixExp_it;//中缀表达式迭代器

    for(InfixExp_it = InfixExp->begin(); InfixExp_it != InfixExp->end(); InfixExp_it++)
    {
        if (!isOper(*InfixExp_it))     //操作数
            postfixExp->push_back(*InfixExp_it);
        else //操作符
        {
            if (mystack.empty())//栈为空,压入操作符                    
                mystack.push(*InfixExp_it);
            else if(isHigh(mystack.top(),*InfixExp_it)) //栈顶操作符优先级高或相等,比如栈顶为*,当前操作符为+,则弹出*                    
            {
                //非闭括号
                //弹出栈中操作符直到栈顶操作数优先级低于当前读入操作数
                //压入当前读入操作符
                if (*InfixExp_it !=  ')')
                {
                    do
                    {
                        postfixExp->push_back(mystack.top());
                        mystack.pop();
                    }while((!mystack.empty()) && (isHigh(mystack.top(), *InfixExp_it)));

                    mystack.push(*InfixExp_it);
                }
                else //闭括号                        
                {
                    while((!mystack.empty()) && (mystack.top() != '('))//弹出直到开括号                            
                    {
                        postfixExp->push_back(mystack.top());
                        mystack.pop();
                    }

                    if ((!mystack.empty()) && (mystack.top()== '('))
                        mystack.pop();
                }
            }
            else if(!isHigh(mystack.top(), *InfixExp_it))//栈顶操作符优先级低, 比如栈顶为+,而当前读入*                    
            {
                mystack.push(*InfixExp_it); //压入当前读入操作符                    
            }
        }
    }

    while(!mystack.empty()) //把栈中剩余的操作符依次弹出            
    {
        postfixExp->push_back(mystack.top());
        mystack.pop();
    }
}

//计算后缀表达式的值
int CalculateValueOfPostfix(vector<char> *PostFix)
{
    int Value;
    bool flag = false;
    stack<char> mystack;
    vector<char>::iterator PostFix_iter;

    if(NULL == PostFix)
    {
        flag = true;
        return -1;
    }
    
    for(PostFix_iter = PostFix->begin(); PostFix_iter != PostFix->end(); ++PostFix_iter)
    {
        int num1, num2;
        
        if(isOper(*PostFix_iter))//操作符
        {
            num2 =(int)( mystack.top() - '0');
            mystack.pop();
            num1 =(int)( mystack.top() - '0');
            mystack.pop();
            //这里只能处理数字是一位的情况,多位数的情况需改进
            switch(*PostFix_iter)
            {
                case '+':
                    Value = num1 + num2;
                    break;
                case '-':
                    Value = num1 - num2;
                    break;
                case '*':
                    Value = num1 * num2;
                    break;
                case '/':
                    Value = num1 / num2;
                    break;
            }
            
            mystack.push((char)(Value + '0'));
        }
        else //操作数
        {
            mystack.push(*PostFix_iter);
        }

    }

    Value = (int)(mystack.top() - '0');
    mystack.pop();

    return Value;    
}

int _tmain(int argc, _TCHAR* argv[])
{
    
    vector <char> InfixExp;//中缀表达式
    vector <char> postfixExp;//后缀表达式
    int val;

    do
    {
        cout << "Please input a formula: " <<endl;
        
        input(&InfixExp);
        output(&InfixExp);

        InfixToPostfix(&InfixExp, &postfixExp);

        output2(&postfixExp);
        cout<<endl;

        val = CalculateValueOfPostfix(&postfixExp);
        cout<<"val="<<val<<endl;

        InfixExp.clear();
        postfixExp.clear();
        //清空栈、中缀表达式和后缀表达式
    }while(true);
    
    system("pause");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值