-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathInfixToPostfix.java
More file actions
139 lines (118 loc) · 2.47 KB
/
InfixToPostfix.java
File metadata and controls
139 lines (118 loc) · 2.47 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
import java.util.Scanner;
class Stack {
int Capacity;
int top;
char s[];
Stack(int n)
{
Capacity=n;
top=-1;
s=new char[Capacity];
}
public boolean isEmpty()
{
if(top==-1)
return true;
else
return false;
}
public char peek()
{
return s[top];
}
void push(char x)
{
if(top==Capacity-1)
return;
else
top++;
s[top]=x;
}
char pop()
{ char popped;
popped=s[top];
top--;
return popped;
}
int opPrec(char op)
{
switch (op)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
return -1;
}
void display()
{
for(int i=0;i<=top;i++)
System.out.println(s[i]);
}
}
public class InfixToPostfix {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int N=sc.nextInt();
char[] infix = new char[N];
char[] postfix= new char[N];
Stack st=new Stack(N);
int i=0,len=0;
for(int k=0;k<N;k++)
{
infix[k]=sc.next().charAt(0);
postfix[k]=' ';
}
/*for(int j=0;j<N;j++)
{
System.out.print(postfix[j]+"-");
}*/
for(int j=0;j<N;j++)
{
char s=infix[j];
if(Character.isDigit(s)==true)
{
postfix[i]=s;
i++;
}
else
{
if(s=='(')
st.push(s);
else if(s==')')
{
while(!st.isEmpty()&&st.peek()!='(')
{
postfix[i]=st.pop();
i++;
}
st.pop();// for removing "("
}
else
{
while (!st.isEmpty() && st.opPrec(s) < st.opPrec(st.peek()))
{
postfix[i] = st.pop();
i++;
}
st.push(s);
}
}
}
while(!st.isEmpty())
{
if(i<N)
{postfix[i]=st.pop();i++;}
else
System.out.println("error");
}
for(int j=0;j<N;j++)
{
System.out.print(postfix[j]+" ");
}
}
}