代码拉取完成,页面将自动刷新
package Project.Arithmetic;
import java.util.*;
public class InfixToSuffix
{
private Stack<String> stack;
private List<String> list;
private String message, Message = "";
public InfixToSuffix() {
stack = new Stack<String>(); // Store operator
list = new ArrayList<String>(); // Store operation number and operator
}
public void conversion(String expr) {
String token;
StringTokenizer tokenizer = new StringTokenizer(expr);
while (tokenizer.hasMoreTokens()) {
// If tokenizer has the next value, loop and assign value.
token = tokenizer.nextToken();
if (token.equals("(")) {
// If the value of the token is the left parenthesis, then the stack
stack.push(token);
}else if (token.equals("+") || token.equals("-")) {
// If the value of token is "+" or "-", once again determine whether the stack is empty.
if (!stack.empty()){
// If the stack is not empty, judge what is the top element of the stack
if (stack.peek().equals("(")) {
// If the top of the stack is "(", the operator enters the stack
stack.push(token);
}else{
// Otherwise, remove the stack top elements first, add them to the list,
// and then stack the operators into the stack.
list.add(stack.pop());
stack.push(token);
}
}else {
// Otherwise the operator enters the stack
stack.push(token);
}
}else if (token.equals("*") || token.equals("÷")){
// If the value of token is "*" or "÷", it again determines whether the stack is empty.
if (!stack.empty()) {
// If the stack is not empty, judge what is the top element of the stack
if (stack.peek().equals("*") || stack.peek().equals("÷")) {
// If the top of the stack is "*" or "÷", remove the stack top elements first,
// add them to the list, and then stack the operators into the stack.
list.add(stack.pop());
stack.push(token);
}else {
// In addition, the operator directly enters the stack.
stack.push(token);
}
}else {
// If the stack is empty, the operator goes directly to the stack
stack.push(token);
}
} else if (token.equals(")")) {
// If encounter "), starts to circulate
while (true) {
// Remove the top element of the stack and assign it to A
String A = stack.pop();
if (!A.equals("(")) {
// If A is not "(", it is added to the list
list.add(A);
} else {
// If A is "(", exit the loop
break;
}
}
}else {
// If it is an arithmetic number, enter the list
list.add(token);
}
}
while (!stack.empty()) {
// Remove elements from the stack and add them to the list until the stack is empty.
list.add(stack.pop());
}
ListIterator<String> li = list.listIterator();
while (li.hasNext()) {
Message += li.next() + " ";
// The elements in iterator are taken out in turn, and spaces are used as separators.
li.remove();
}
message = Message;
}
public String getMessage() {
return message;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。