forked from sunnyshahabuddin/Coding-Ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopost.java
104 lines (99 loc) · 1.61 KB
/
topost.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
94
95
96
97
98
99
100
101
102
103
import java.io.*;
import java.util.*;
import java.lang.*;
class stack
{
char[] arr;
int top,size;
stack(int n)
{
arr=new char[n];
top=-1;
size=n;
}
public void push(char f)
{
arr[++top]=f;
}
public char pop()
{
return arr[top--];
}
public char peek()
{
return arr[top];
}
public boolean isempty()
{
return top==-1;
}
}
class postfix
{
int pre(char c)
{
switch(c)
{
case'+':
case'-':
return 1;
case'*':
case'/':
return 2;
}
return -1;
}
String inftopof(String exp)
{
String result=new String();
try{
stack sk=new stack(exp.length());
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i);
if(Character.isLetterOrDigit(c))
result+=c;
else if(c=='(')
sk.push(c);
else if(c==')')
{
while(!sk.isempty()&&sk.peek()!='(')
result+=sk.pop();
if(!sk.isempty()&&sk.peek()!='(')
System.out.println("INvalid Expression");
else
sk.pop();
}
else
{
while(!sk.isempty() && pre(c)<=pre(sk.peek()))
{
if(sk.peek()=='(')
return "InValid Expression";
result+=sk.pop();
}
sk.push(c);
}
}
while (!sk.isempty())
{
if(sk.peek()=='(')
return "Invalid ExPression";
result+=sk.pop();
}
return result;
}catch (Exception e) {System.out.println("Invalid ExpresSion");}
return "";
}
}
class topost
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
postfix obj=new postfix();
System.out.println("ENTER INFIX EXPRESSION TO CONVERT TO POSTFIX :");
String str=sc.nextLine();
System.out.println("POSTFIX EXPRESSION IS : "+obj.inftopof(str));
}
}