Skip to content

Commit dac4822

Browse files
Merge pull request codemistic#483 from ManikSingh29/Manik
Added Infix to Postfix
2 parents c16727d + 70349fc commit dac4822

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
2.17 KB
Binary file not shown.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import java.util.Stack;
2+
import java.util.Scanner;
3+
public class InfixToPostfix_byManik {
4+
5+
static int precedence(char c){
6+
switch (c){
7+
case '+':
8+
case '-':
9+
return 1; //Since '+'&'-' are of same precedence
10+
case '*':
11+
case '/':
12+
return 2;
13+
case '^':
14+
return 3;
15+
}
16+
return -1;
17+
}
18+
19+
static String infixToPostFix(String expression){
20+
21+
String result = "";
22+
Stack<Character> stack = new Stack<>();
23+
for (int i = 0; i <expression.length() ; i++) {
24+
char c = expression.charAt(i);
25+
26+
//check if char is operator
27+
if(precedence(c)>0){
28+
while(stack.isEmpty()==false && precedence(stack.peek())>=precedence(c)){
29+
result += stack.pop();
30+
}
31+
stack.push(c);
32+
}else if(c==')'){
33+
char x = stack.pop();
34+
while(x!='('){
35+
result += x;
36+
x = stack.pop();
37+
}
38+
}else if(c=='('){
39+
stack.push(c);
40+
}else{
41+
//character is neither operator nor (
42+
result += c;
43+
}
44+
}
45+
for (int i = 0; i <=stack.size() ; i++) {
46+
result += stack.pop();
47+
}
48+
return result;
49+
}
50+
51+
public static void main(String[] args) {
52+
Scanner sc=new Scanner(System.in);
53+
System.out.println("Enter the Expression");
54+
String Input=sc.next();
55+
System.out.println("Infix Expression: " + Input);
56+
System.out.println("Postfix Expression: " + infixToPostFix(Input));
57+
}
58+
}

0 commit comments

Comments
 (0)