I am pretty sure, that stacks are used for building PRN and '(' are ignored, but it does not seem to be the case. For example:
- input 1: 52+(1+2)*4-3
- input 2: 52+((1+2)*4)-3
- input 3: (52+1+2)*4-3
Input 1 and input 2 output should be the same, and input 1 and input 3 should differ.
- output 1: 52 1 2 + 4 3 - * +
- output 2: 52 1 2 + 4 * 3 - +
- output 3: 52 1 2 + 4 3 - * +
public static String Infix2(String input) {
char[] in = input.toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length; i++)
switch (in[i]) {
case '+':
case '*':
case '-':
out.append(' ');
stack.push(in[i]);
break;
case ' ':
case '(':
break;
case ')':
out.append(' ');
out.append(stack.pop());
break;
default:
out.append(in[i]);
break;
}
while (!stack.isEmpty()) {
out.append(' ');
out.append(stack.pop());
}
return out.toString();
}
Assuming that i want input 1 and 3 also to work, what approach should i use?
edit:
After the changes '+','-','*' and '/' worked for given inputs.
public static String Infix2(String input) {
if (input == null)
return "";
char[] in = input.toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length; i++)
switch (in[i]) {
case '+':
case '-':
while (!stack.empty()
&& (stack.peek() == '*' || stack.peek() == '/'))
out.append(' ').append(stack.pop());
case '*':
case '/':
out.append(' ');
case '(':
stack.push(in[i]);
case ' ':
break;
case ')':
while (!stack.empty() && stack.peek() != '(')
out.append(' ').append(stack.pop());
if (!stack.empty())
stack.pop();
break;
default:
out.append(in[i]);
break;
}
while (!stack.isEmpty())
out.append(' ').append(stack.pop());
return out.toString();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…