-
Notifications
You must be signed in to change notification settings - Fork 0
/
postfix.java
118 lines (105 loc) · 2.43 KB
/
postfix.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//package pars;
import java.util.*;
public class postfix {
public static int top=-1;
public static char s2[]=new char[100];
public static char s3[]=new char[100];
static int count;
public char[] post(char s1[]){
int i;
count=0;
//char s1[]=s.toCharArray();
for(i=0;i<s1.length;i++)
{
if(s1[i]=='+') {
p(s1[i]);
}
else if(s1[i]=='-')
{ p(s1[i]);}
else if(s1[i]=='*')
{p(s1[i]);}
else if(s1[i]=='/')
{p(s1[i]);}
else if(s1[i]=='(')
p(s1[i]);
else if(s1[i]==')')
p(s1[i]);
else if(s1[i]=='_')
p(s1[i]);
else if(s1[i]=='^')
p(s1[i]);
else
{
System.out.print(s1[i]);
s3[count]=s1[i];
count++;
}
}
while(top!=-1)
{
if(s2[top]!='(')
System.out.print(s2[top]);
s3[count]=s2[top];
top--;
count++;
}
s3[count]='?';
/*
for(int k=0;s3[k]!='?';k++)
System.out.println();
*/
return s3;
//A * (B + C * D) + E
}
public static int precedence(char a)
{
if(a=='+')
return 1;
if(a=='-')
return 1;
if(a=='*')
return 2;
if(a=='/')
return 2;
if(a=='_')
return 3;
if(a=='(')
return 5;
if(a=='^')
return 4;
return 0;
}
public static void p(char a)
{
if(top==-1)
push(a);
else if(a==')')
{
while(s2[top]!='(')
{
System.out.print(s2[top]);
s3[count]=s2[top];
top--;
count++;
}
top--;
}
else if(precedence(a)>precedence(s2[top]))
push(a);
else if(s2[top]=='(')
push(a);
else
{
System.out.print(s2[top]);
s3[count]=s2[top];
top--;
count++;
push(a);
}
}
public static void push(char a)
{
top=top+1;
s2[top]=a;
}
}