我编写了代码,将后缀转换为完全括号的后缀,作为我家庭作业的一部分,但此代码只能将后缀表达式转换为个位数。我需要帮助转换包含 2 位或更多位数字的中缀表达式。
//Here's my code. My class doesn't use collection in JAVA.
//Classes and Interfaces for stack, list, and tree are provided.
private static final String DIGITS = "0123456789";
public static String convertPostfixtoInfix(String toPostfix)
{
LinkedStack<String> s = new LinkedStack<>();
for(int i=0; i<toPostfix.length(); i++)
{
if(DIGITS.indexOf(toPostfix.charAt(i)) != -1)
{
s.push(toPostfix.charAt(i)+"");
}
else if(toPostfix.charAt(i) == " ");{}//do nothing for blank.
else
{
String temp = "";
temp += toPostfix.charAt(i);
String num1 = s.top();
s.pop();
String num2 = s.top();
s.pop();
s.push("(" + num2 + temp + num1 + ")");
}
}
return s.top();//top() is same as peek() method.
}
例如,使用此代码,
输入: 4 5 - 9 2 1 + / *
输出: ((4-5)*(9/(2+1)))
输入: 40 5 - 9 20 1 + / *
输出: (9*(2/(0+1)))
jeck猫
相关分类