-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfix.java
More file actions
160 lines (126 loc) · 2.3 KB
/
Postfix.java
File metadata and controls
160 lines (126 loc) · 2.3 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
public class Postfix
{
public static String convertToPostfix(String infix)
{
LinkedStack<Character> stack = new LinkedStack<Character>();
StringBuilder exp = new StringBuilder();
char c = ' ';
for (int i = 0; i < infix.length(); i++)
{
c = infix.charAt(i);
if(oper(c))
{
if(c =='(')
{
stack.push(c);
}
else if(c==')')
{
char stackTop = stack.pop();
while(stackTop != '(')
{
exp.append(stackTop);
stackTop = stack.pop();
}
}
else
{
while(!stack.isEmpty() && !order(c, stack.peek()))
{
exp.append(stack.pop());
}
stack.push(c);
}
}
else
{
exp.append(c);
}
}
while(!stack.isEmpty())
{
exp.append(stack.pop());
}
return exp.toString();
}
private static boolean oper(char c)
{
return c=='^'|| c=='*' || c=='/'|| c=='-' || c=='+' || c=='(' || c==')';
}
private static boolean order(char op1, char op2)
{
if((op1=='*' && op2=='+') ||
(op1=='*' && op2=='-') ||
(op1=='/' && op2=='+')||
(op1=='/' && op2=='-')||
(op1=='^' && op2=='+')||
(op1=='^' && op2=='-')||
(op1=='^' && op2=='*')||
(op1=='^' && op2=='/')||
(op2 =='('))
{
return true;
}
return false;
}
public static int evalutePostfix(String postfix)
{
StackInterface<Integer> stack = new LinkedStack<Integer>();
char ch = ' ';
for(int i=0;i<postfix.length();i++)
{
ch=postfix.charAt(i);
if(ch!='+'&&ch!='-'&&ch!='/'&&ch!='*'&&ch!='^')
{
stack.push((int)ch-'0');
}
else
{
if(ch=='^')
{
int oprand1=stack.pop();
int oprand2=stack.pop();
int result=solution(oprand2,oprand1,ch);
stack.push(result);
}
else
{
int oprand2 = stack.pop();
int oprand1 = stack.pop();
int result=solution(oprand1,oprand2,ch);
stack.push(result);
}
}
}
return stack.peek();
}
private static int solution(int one, int two, char op)
{
int data=0;
if(op =='^')
{
data=(int)Math.pow(one,two);
}
else if(op =='*')
{
data= one*two;
}
else if(op =='/')
{
data= one/two;
}
else if(op =='-')
{
data= one-two;
}
else if(op=='+')
{
data= one+two;
}
else
{
data= 0;
}
return data;
}
}