首页 > 试题广场 >

对一个整数的四则运算后缀表达式,请写函数将其打印成日常我们使

[问答题]
对一个整数的四则运算后缀表达式,请写函数将其打印成日常我们使用的中缀表达式。如对ab+c*,打印出 (a+b)*c 。后缀表达式以一个列表形式作为函数输入,列表的元素为数字或加减乘除操作符。
public class Postfix {
 
    private static String parseStr(String str) {
        // TODO Auto-generated method stub
        StringBuffer buf=new StringBuffer();
        Stack<String> st=new Stack<String>();
        String[] data=str.split(" ");
        buf.append(data[0]);
        for (int i=1;i<data.length;i++){
            switch (data[i]) {
            case "*":
                buf.append(data[i]);
                buf.append(st.pop());
                break;
            case "/":
                buf.append(data[i]);
                buf.append(st.pop());
                break;
            case "+":
                buf.insert(0, "(");
                buf.append(data[i]);
                buf.append(st.pop());
                buf.append(")");
                break;
            case "-":
                buf.insert(0, "(");
                buf.append(data[i]);
                buf.append(st.pop());
                buf.append(")");
                break;
            default:
                st.push(data[i]);
                break;
            }
        }
        return buf.toString();
    }
    
 public static void main(String[] args) {
    Scanner scan=new Scanner(System.in);
    String str=scan.nextLine();
    String out=parseStr(str);
    System.out.println(out);
}

}

发表于 2018-01-25 23:41:44 回复(2)
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <map>
using namespace std;

void get_postfix(vector<string>& postfix)
{
    postfix.clear();
    string line, op_op;
    getline(cin, line);
    istringstream sin(line);
    while (sin >> op_op)
    {
        postfix.push_back(op_op);
    }
}

void init_operators(map<string, int>& optors)
{
    optors.clear();
    optors["+"] = 100;
    optors["-"] = 100;
    optors["*"] = 200;
    optors["/"] = 200;
}

bool is_operator(const map<string, int>& optors, const string& str)
{
    auto cit = optors.find(str);
    if (cit != optors.end())
    {
        return true;
    }
    else
    {
        return false;
    }
}

void post_to_in(const vector<string>& postfix, string& infix, map<string, int>& optors)
{
    infix.clear();
    if (postfix.empty())
    {
        return;
    }
    vector<string> post_optors; // 按照后缀表达式操作符的顺序,记录表达式中的操作符
    for (auto i = 0; i != postfix.size(); ++i)
    {
        if (is_operator(optors, postfix[i]))
        {
            post_optors.push_back(postfix[i]);
        }
    }
    auto pos = 0; // 记录当前操作符在post_optors中的位置

    // 表达式栈
    stack<string> exp_stk;
    string a, b, c;

    for (auto i = 0; i != postfix.size(); ++i)
    {
        if (!is_operator(optors, postfix[i]))
        {
            exp_stk.push(postfix[i]);
        }
        else
        {
            switch (postfix[i][0])
            {
            case '+':
            case '-':
            case '*':
            case '/':
                b = exp_stk.top();
                exp_stk.pop();
                a = exp_stk.top();
                exp_stk.pop();

                // 加括号 || 不加括号
                ++pos;
                if (pos < post_optors.size() && optors[post_optors[pos]] > optors[postfix[i]])
                {
                    c = "( " + a + " " + postfix[i] + " " + b + " )";
                }
                else
                {
                    c = a + " " + postfix[i] + " " + b;
                }
                
                exp_stk.push(c);
                break;

            default:
                break;
            }
        }
    }
    if (exp_stk.size() == 1)
    {
        infix = exp_stk.top();
    }
    else
    {
        infix = "后缀表达式非法,转换失败!";
    }
}

void display(const vector<string>& strs)
{
    for (auto cit = strs.begin(); cit != strs.end(); ++cit)
    {
        cout << *cit << ' ';
    }
    cout << endl;
}

int main()
{
    vector<string> postfix;
    string infix;

    map<string, int> optors;
    init_operators(optors);

    while (1)
    {
        get_postfix(postfix);

        post_to_in(postfix, infix, optors);

        display(postfix);
        cout << infix << endl;
        cout << endl;
    }

    return 0;
}
发表于 2019-03-19 20:12:40 回复(0)
class Main {   public static void main(String []args){  parseStr("ab*c*d+a+c/");   }   public static void parseStr(String string){  if(null == string || "".equals(string)) return;  StringBuilder sb = new StringBuilder();  String arr[] = string.split("");    for(int i = 0;i<arr.length;i++){  switch (arr[i]) {  case "+" :  if(sb.length() == 0)sb.append(arr[i-2]+"+"+arr[i-1]);  else sb.append("+"+arr[i-1]);  break;  case "-" :  if(sb.length() == 0)sb.append(arr[i-1]+"-"+arr[i-2]);  else sb.append("-"+arr[i-1]);  break;  case "*" :  if((sb.indexOf("+")>0 || sb.indexOf("-")>0)&& sb.indexOf(")")<0) {  sb.append(")");  sb.insert(0,"(");  } else if((sb.indexOf("*")>0 || sb.indexOf("/")>0) && sb.lastIndexOf("*") != (sb.length()-2) && sb.lastIndexOf("/") != (sb.length()-2) ){  System.out.println(sb.lastIndexOf("*")+" : "+sb.length());  sb.append(")");  sb.insert(0,"(");  }  if (sb.length() == 0)  sb.append(arr[i - 1] + "*" + arr[i - 2]);  else  sb.append("*" + arr[i - 1]);  break;  case "/" :  if((sb.indexOf("+")>0 || sb.indexOf("-")>0)&& sb.indexOf(")")<0) {  sb.append(")");  sb.insert(0,"(");  } else if((sb.indexOf("*")>0 || sb.indexOf("/")>0) && sb.lastIndexOf("*") != (sb.length()-2) && sb.lastIndexOf("/") != (sb.length()-2) ){  System.out.println(sb.lastIndexOf("*")+" : "+sb.length());  sb.append(")");  sb.insert(0,"(");  }  if(sb.length() == 0)sb.append(arr[i-1]+"/"+arr[i-2]);  else sb.append("/"+arr[i-1]);  break;  default:  break;  }  }  System.out.println(sb.toString());  }   }
发表于 2018-01-24 11:21:03 回复(0)