📜  前缀到中缀转换

📅  最后修改于: 2022-05-13 01:57:08.424000             🧑  作者: Mango

前缀到中缀转换

:如果运算符出现在表达式的操作数之间,则表达式称为中缀表达式。简单的形式(operand1 运算符 )。
示例 : (A+B) * (CD)

前缀:如果运算符出现在表达式中的操作数之前,则表达式称为前缀表达式。简单的形式(运算符 )。
示例:*+AB-CD(中缀:(A+B) * (CD))

给定一个前缀表达式,将其转换为中缀表达式。
计算机通常以前缀或后缀(通常是后缀)进行计算。但是对于人类来说,中缀表达式比前缀更容易理解。因此,转换是人类理解的需要。

例子:

Input :  Prefix :  *+AB-CD
Output : Infix : ((A+B)*(C-D))

Input :  Prefix :  *-A/BC-/AKL
Output : Infix : ((A-(B/C))*((A/K)-L))

前缀到中缀的算法

  • 以相反的顺序读取前缀表达式(从右到左)
  • 如果符号是操作数,则将其压入堆栈
  • 如果符号是运算符,则从堆栈中弹出两个操作数
    通过连接两个操作数和它们之间的运算符来创建一个字符串。
    字符串=(操作数 1 +运算符数 + 操作数 2)
    并将生成的字符串推回 Stack
  • 重复上述步骤,直到 Prefix 表达式结束。
  • 最后堆栈将只有 1 个字符串,即结果字符串
C++
// C++ Program to convert prefix to Infix
#include 
#include 
using namespace std;
 
// function to check if character is operator or not
bool isOperator(char x) {
  switch (x) {
  case '+':
  case '-':
  case '/':
  case '*':
  case '^':
  case '%':
    return true;
  }
  return false;
}
 
// Convert prefix to Infix expression
string preToInfix(string pre_exp) {
  stack s;
 
  // length of expression
  int length = pre_exp.size();
 
  // reading from right to left
  for (int i = length - 1; i >= 0; i--) {
 
    // check if symbol is operator
    if (isOperator(pre_exp[i])) {
 
      // pop two operands from stack
      string op1 = s.top();   s.pop();
      string op2 = s.top();   s.pop();
 
      // concat the operands and operator
      string temp = "(" + op1 + pre_exp[i] + op2 + ")";
 
      // Push string temp back to stack
      s.push(temp);
    }
 
    // if symbol is an operand
    else {
 
      // push the operand to the stack
      s.push(string(1, pre_exp[i]));
    }
  }
 
  // Stack now contains the Infix expression
  return s.top();
}
 
// Driver Code
int main() {
  string pre_exp = "*-A/BC-/AKL";
  cout << "Infix : " << preToInfix(pre_exp);
  return 0;
}


Java
// Java program to convert prefix to Infix
import java.util.Stack;
 
class GFG{
 
// Function to check if character
// is operator or not    
static    boolean isOperator(char x)
{
    switch(x)
    {
        case '+':
        case '-':
        case '*':
        case '/':
        case '^':
        case '%':
            return true;
    }
    return false;
}
 
// Convert prefix to Infix expression
public static String convert(String str)
{
    Stack stack = new Stack<>();
     
    // Length of expression
    int l = str.length();
     
    // Reading from right to left
    for(int i = l - 1; i >= 0; i--)
    {
        char c = str.charAt(i);
        if (isOperator(c))
        {
            String op1 = stack.pop();
            String op2 = stack.pop();
             
            // Concat the operands and operator
            String temp = "(" + op1 + c + op2 + ")";
            stack.push(temp);
        }
        else
        {
             
            // To make character to string
            stack.push(c + "");
        }
    }
    return stack.pop();
}
 
// Driver code
public static void main(String[] args)
{
    String exp = "*-A/BC-/AKL";
    System.out.println("Infix : " + convert(exp));
}
}
 
// This code is contributed by abbeyme


Python3
# Python Program to convert prefix to Infix
def prefixToInfix(prefix):
    stack = []
     
    # read prefix in reverse order
    i = len(prefix) - 1
    while i >= 0:
        if not isOperator(prefix[i]):
             
            # symbol is operand
            stack.append(prefix[i])
            i -= 1
        else:
           
            # symbol is operator
            str = "(" + stack.pop() + prefix[i] + stack.pop() + ")"
            stack.append(str)
            i -= 1
     
    return stack.pop()
 
def isOperator(c):
    if c == "*" or c == "+" or c == "-" or c == "/" or c == "^" or c == "(" or c == ")":
        return True
    else:
        return False
 
# Driver code
if __name__=="__main__":
    str = "*-A/BC-/AKL"
    print(prefixToInfix(str))
     
# This code is contributed by avishekarora


C#
// C# program to convert prefix to Infix
using System;
using System.Collections;
 
class GFG{
  
// Function to check if character
// is operator or not    
static bool isOperator(char x)
{
    switch(x)
    {
        case '+':
        case '-':
        case '*':
        case '/':
        case '^':
        case '%':
            return true;
    }
    return false;
}
  
// Convert prefix to Infix expression
public static string convert(string str)
{
    Stack stack = new Stack();
      
    // Length of expression
    int l = str.Length;
      
    // Reading from right to left
    for(int i = l - 1; i >= 0; i--)
    {
        char c = str[i];
         
        if (isOperator(c))
        {
            string op1 = (string)stack.Pop();
            string op2 = (string)stack.Pop();
              
            // Concat the operands and operator
            string temp = "(" + op1 + c + op2 + ")";
            stack.Push(temp);
        }
        else
        {
             
            // To make character to string
            stack.Push(c + "");
        }
    }
    return (string)stack.Pop();
}
  
// Driver code
public static void Main(string[] args)
{
    string exp = "*-A/BC-/AKL";
     
    Console.Write("Infix : " + convert(exp));
}
}
 
// This code is contributed by rutvik_56


Javascript


输出
Infix : ((A-(B/C))*((A/K)-L))