-
Notifications
You must be signed in to change notification settings - Fork 7
/
ReversePolishNotation.java
75 lines (73 loc) · 2.13 KB
/
ReversePolishNotation.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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Iterator;
public class RPN {
static ArrayDeque<Character> ops, out;
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
char[] in = br.readLine().toCharArray();
ops = new ArrayDeque<>();
out = new ArrayDeque<>();
for(char c : in){
if(c == ' ') continue;
else if(isOp(c)){
switch(c){
case '(':
ops.push(c);
break;
case ')':
while(weGood()){
out.push(ops.pop());
}
ops.pop();
break;
case '+':
case '-':
while(weGood()){
out.push(ops.pop());
}
ops.push(c);
break;
case '*':
case '/':
while(weGood() && notAS()){
out.push(ops.pop());
}
ops.push(c);
break;
case '^':
ops.push(c);
break;
}
}
else{
out.push(c);
}
}
while(weGood()) out.push(ops.pop());
Iterator it = out.descendingIterator();
while(it.hasNext()) pw.print(it.next() + " ");
pw.println();
pw.close();
}
static boolean weGood(){
return !ops.isEmpty() && ops.peek() != '(';
}
static boolean notAS(){
return ops.peek() != '+' && ops.peek() != '-';
}
static boolean isOp(char in){
if(in == '^') return true;
if(in == '*') return true;
if(in == '/') return true;
if(in == '+') return true;
if(in == '-') return true;
if(in == '(') return true;
if(in == ')') return true;
return false;
}
}