C++:用栈求逆波兰表达式的值

最初的方法,不是很简便, 其实可以直接遍历整个表达式

// 用栈实现求逆波兰表达式的值

/*********************************************************************
养成先手写算法,再编码修正的习惯:
1.遍历串,分离每个子串并放入vector
2.遍历vector,若是数字则压入栈,否则弹出b,a计算后将结果压入栈
3.输出最终结果
**********************************************************************/

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <cctype>
using namespace std;

// 定义栈
using Stack = struct Stack {
    int top = 0;
    string str[100];
};

// 入栈
bool Push(Stack&, const string);
// 出栈
bool Pop(Stack&, string&);
void ElemToVector(const string&, std::vector<string>&);
void Calc(Stack&, const std::vector<string>&);
inline bool is_digit(const string&);
inline int ConvertToInt(const string&);
inline char ConvertTOChar(const string&);
inline string ConvertToString(const int&);
inline void iCalc(Stack&, string&);


int main(int argc, char** argv)
{
    Stack S;
    std::vector<string> sv;
    string str("234 34+2*$");
    ElemToVector(str, sv);
    Calc(S, sv);
    cout << S.str[0];
    return 0;
}

void iCalc(Stack &S, string &x)
{

    string b, a; // 栈中存放的是字符串
    int nb, na;   
    Pop(S, b); 
    Pop(S, a);
    nb = ConvertToInt(b);
    na = ConvertToInt(a);
    char oper = ConvertTOChar(x);
    switch(oper)
    {
        case '+':
            Push(S, ConvertToString(na+nb));
            break;
        case '-':
            Push(S, ConvertToString(na-nb));
            break;
        case '*':
            Push(S, ConvertToString(na*nb));
            break;
        case '/':
            Push(S, ConvertToString(na/nb));
            break;
    }
}


string ConvertToString(const int &e)
{
    string result;
    stringstream stream;
    stream << e;
    stream >> result;
    return result;

}

char ConvertTOChar(const string& str)
{
    char result;
    stringstream stream;
    stream << str;
    stream >> result;
    return result;
}

int ConvertToInt(const string &str)
{
    int result;
    stringstream stream;
    stream << str;
    stream >> result;
    return result;
}


bool is_digit(const string &str)
{
    for(const auto &x : str)
        if(!isdigit(x)) return false;
    return true;

    // stringstream方法在串一开始有数字但是后面有符号时失效
    // 会把开头的数字全部输入到数字变量中
    // int temp;
    // istringstream istream(str);
    // if(istream >> temp) {
    //  cout << "yes" << temp << endl;
    //  return true;    
    // }
    // return false;

}


void Calc(Stack &S, const std::vector<string> &sv)
{
    for(const auto &x : sv) {
        if(is_digit(x)) {
            Push(S, x);
        }
        else {
            // 若不是纯数字,则遍历
            string sum;
            for(const auto &c : x) {
                if(c == '$') continue;
                // 若为连续数字,存入字符串
                if(isdigit(c)){
                    string str(1,c);
                    sum += str;
                }
                else {
                // 若数字字符串结束, 将数字字符串压入栈
                    if(sum != "") {
                        Push(S, sum);
                        sum = "";
                    }
                    string oper(1, c);
                    iCalc(S, oper);
                }   
            }
        }
    }
}

void ElemToVector(const string &str, std::vector<string> &sv)
{
    istringstream istream(str);
    string elem;
    while(istream >> elem)
        if (elem != "$") sv.push_back(elem);
}


bool Push(Stack &S, const string e)
{
    S.str[S.top++] = e;
    return true;
}

bool Pop(Stack &S, string &e)
{
    e = S.str[--S.top];
    return true;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
是一种常见的数据结构,用于实现逆波兰表达式逆波兰表达式是一种不需要括号来表示运算优先级的表达式形式,它将操作符放在操作数的后面。 在C++中,可以使用栈来实现逆波兰表达式的算法。具体步骤如下: 1. 创建一个空,用于存储操作数和中间结果。 2. 从左到右遍历逆波兰表达式的每个元素。 3. 如果当前元素是操作数,则将其入。 4. 如果当前元素是操作符,则从中弹出两个操作数,并根据操作符进行计算,将计算结果入。 5. 重复步骤3和4,直到遍历完所有元素。 6. 最后,中剩下的唯一元素就是逆波兰表达式的求结果。 下面是一个示例的C++代码实现: ```cpp #include <iostream> #include <stack> #include <string> using namespace std; int evaluateRPN(string expression) { stack<int> operands; for (char c : expression) { if (isdigit(c)) { operands.push(c - '0'); } else if (c == '+' || c == '-' || c == '*' || c == '/') { int operand2 = operands.top(); operands.pop(); int operand1 = operands.top(); operands.pop(); int result; switch (c) { case '+': result = operand1 + operand2; break; case '-': result = operand1 - operand2; break; case '*': result = operand1 * operand2; break; case '/': result = operand1 / operand2; break; } operands.push(result); } } return operands.top(); } int main() { string expression = "34+2*"; int result = evaluateRPN(expression); cout << "Result: " << result << endl; return 0; } ``` 这段代码实现了一个简单的逆波兰表达式算法。它首先创建了一个来存储操作数和中间结果。然后,遍历逆波兰表达式的每个字符,如果是操作数则入,如果是操作符则从中弹出两个操作数进行计算,并将结果入。最后,返回中剩下的唯一元素作为求结果。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值