中缀表达式转后缀表达式

来源:互联网 发布:淘宝网1.4 餐桌 编辑:程序博客网 时间:2024/06/05 14:52

这是Eden题目Expression Conversion by Linked Stack(for homework)的中缀表达式转后缀表达式源文件的我自己写的实现部分,不能直接使用,但是可以从中看思路。

主要是对输入的字符分情况进行处理,详细方法在代码的注释中.

#ifndef MIDTOLAST_CPP#define MIDTOLAST_CPP#include "MidToLast.h"#include <iostream>#include "stack.h"#include <string>#include <sstream>using namespace std;string MidToLast::transfer(string str) {    stringstream out;// 存储输出的后缀表达式    Stack holder; //建立个栈,要用    char temp = '\0';    for (int i = 0; i < str.length(); i++) { // 循环,对输入的每个字符进行处理        temp = str[i];        if ('0' <= temp && temp <= '9') {  //  1.若是操作数,直接输出            out << temp;        } else if ('(' == temp) {  // 2.若是左括号,入栈            holder.push(temp);        } else if (')' == temp) {// 3.若是右括号,一直出栈并输出,直到遇到左括号,但是左括号只出栈不输出            while ('(' != holder.top()) {                out << holder.top();                holder.pop();            }            holder.pop();        } else {// 4.如果遇到操作符 +、-、*、/            if (holder.empty()) {// 4.1 栈空时,直接入栈                holder.push(temp);            } else if ('+' == temp || '-' == temp) {// 4.2栈不空时,出栈并输出栈中所有优先级大于等于该运算符的运算符                while (false == holder.empty()                    && (holder.top() == '+' || '-' == holder.top()                        || '*' == holder.top() || '/' == holder.top())) {                        out << holder.top();                        holder.pop();                    }                holder.push(temp);            } else if ('*' == temp || '/' == temp) {// 4.2栈不空时,出栈并输出栈中所有优先级大于等于该运算符的运算符                while (false == holder.empty()                    && ('*' == holder.top() || '/' == holder.top())) {                        out << holder.top();                        holder.pop();                    }                holder.push(temp);            }        }    }    while (!holder.empty()) { // 5.最后全部出栈        out << holder.top();        holder.pop();    }    return out.str(); // 输出后缀表达式}#endif
0 0