英文:
infix to postfix without loops inside loops
问题
List<String> infix2Postfix(List<String> infix) {
Stack<String> opStack = new Stack<>();
List<String> outPut = new ArrayList<>();
for (String inComing : infix) {
if (OPERATORS.contains(inComing)) {
if (opStack.empty() || opStack.peek().equals("(")) {
// Handle case when operator stack is empty or contains "("
// ...
} else {
// Handle other cases when operators are present
// ...
}
} else if ("()".contains(inComing)) {
if (")".equals(inComing)) {
// Handle closing parenthesis
// ...
} else {
opStack.add(inComing);
}
} else {
outPut.add(inComing);
}
}
if (opStack.contains("(")) {
throw new IllegalArgumentException(MISSING_OPERATOR);
}
while (!opStack.empty()) {
outPut.add(opStack.pop());
}
return outPut;
}
请注意,我已经只保留了代码的翻译部分,而删除了问题和其他内容。如果您有任何更多的问题或需要进一步的帮助,请随时提问。
英文:
So i have an assignment to write infix to postfix method without any nested loops (loops in loops) and i didn't notice that and i wrote long method with nested loops, any idea how to fix it? here is the code
How can i divide them into smaller method while have stack?
List<String> infix2Postfix(List<String> infix) {
Stack<String> opStack = new Stack<>();
List<String> outPut = new ArrayList<>();
for (String inComing : infix) {
// When incoming is one of -,+,*,/,^
if (OPERATORS.contains(inComing)) {
if (opStack.empty() || opStack.peek().equals("(")) {
....
} else {
....
if (inComingP == 4 && inComingP == operatorP) {
....
} else if (inComingP == operatorP) {
...
} else if (inComingP < operatorP) {
while (!opStack.empty() && !opStack.peek().equals("(")) {
...
}
opStack.push(inComing);
} else {
opStack.push(inComing);
}
}
}
// when incoming is one of "(" , ")"
else if ("()".contains(inComing)) {
if (")".equals(inComing)) {
while (opStack.size() != 0 && !opStack.peek().equals("(")) {
...
}
if (opStack.size() == 0) {
...
} else {
opStack.pop();
}
} else {
opStack.add(inComing);
}
} else {
outPut.add(inComing);
}
}
if (opStack.contains("(")) {
throw new IllegalArgumentException(MISSING_OPERATOR);
}
while (!opStack.empty()) {
outPut.add(opStack.pop());
}
return outPut;
}
专注分享java语言的经验与见解,让所有开发者获益!
评论