-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfixToPostfixSolve.java
93 lines (89 loc) · 2.02 KB
/
InfixToPostfixSolve.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.Stack;
public class InfixToPostfixSolve implements Requirement1_OutputGetter
{
private String inputString;
private String outputString;
public InfixToPostfixSolve(){
this.inputString = "";
this.outputString = "";
}
public InfixToPostfixSolve(String inputString){
this.inputString = inputString;
this.outputString = "";
}
public void setInputString(String inputString){
this.inputString = inputString;
}
public String getOutputString() {
this.outputString = infixToPostfix();
return outputString;
}
private String infixToPostfix()
{
String postfix = "";
Stack <String> stack = new Stack<String>();
stack.push(" ");
String [] tokens = stringTokenizer(this.inputString);
for(int i=0; i<tokens.length; i++)
{
if(isNum(tokens[i]))
{
postfix = postfix + tokens[i] + " ";
}
else if(tokens[i].equals("("))
{
stack.push(tokens[i]);
}
else if(tokens[i].equals(")"))
{
while(!stack.peek().equals("("))
{
postfix = postfix + stack.pop() + " ";
}
stack.pop();
}
else if(priorityOfOperator(tokens[i]) > priorityOfOperator(stack.peek()))
{
stack.push(tokens[i]);
}
else if(priorityOfOperator(tokens[i]) <= priorityOfOperator(stack.peek()))
{
while(priorityOfOperator(tokens[i]) <= priorityOfOperator(stack.peek()))
{
postfix = postfix + stack.pop() + " ";
}
stack.push(tokens[i]);
}
}
while(!(stack.peek().equals(" ")))
{
postfix = postfix + stack.pop() + " ";
}
return postfix;
}
private String [] stringTokenizer(String str)
{
String [] tokens = str.split(" ");
return tokens;
}
private boolean isNum(String c)
{
return c.matches("-?\\d+(\\.\\d+)?");
}
private int priorityOfOperator(String op)
{
if(op.equals("+")||op.equals("-"))
{
return 1;
}
else if(op.equals("*")||op.equals("/"))
{
return 2;
}
else if(op.equals("^"))
{
return 3;
}
return -1;
}
}