forked from Git-Hero/Level3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infixToPostfix.c
162 lines (157 loc) · 2.04 KB
/
infixToPostfix.c
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
161
162
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#define N 100
typedef struct stack
{
int top;
char A[N];
}stack;
bool empty(stack *ps)
{
if(ps->top==0)
return true;
else
return false;
}
void push(stack *ps, int x)
{
if(ps->top==N-1)
{
printf("Overflow\n");
return;
}
(ps->top)++;
ps->A[(ps->top)]=x;
}
char pop(stack *ps)
{
if(empty(ps))
{
printf("Underflow\n");
return ;
}
char a = ps->A[ps->top];
ps->top--;
return a;
}
void print(stack *ps,int d)
{
int t= ps->top;
while(t>=0)
{
if(d)
printf("%d ",ps->A[t]);
else
printf("%c ",ps->A[t]);
t--;
}
printf("\n");
}
bool isoperand(char c)
{
switch(c)
{
case '+' : return true;
case '-' : return true;
case '*' : return true;
case '/' : return true;
case '^' : return true;
case '(' : return true;
case ')' : return true;
default : return false;
}
}
int pr ( char a)
{
int c;
if(a=='+'||a=='-')
c=1;
else if(a=='*'||a=='/')
c=2;
return c;
}
bool prcd(char a, char b)
{
/* returns true if precedence of char a is more than that of b*/
}
int main()
{
int z;
scanf("%d",&z);
while(z--)
{
char a;
stack s;
char str[100][100]={'\0'};
char si[100][100]={'\0'};
int f=0;
int o=0;
s.top=-1;
int j=0,k=0,i;
while(1)
{
a=getchar();
if(a==' ')
{
j=0;
k++;
}
else if(a=='?')
{
break;
}
else
{
str[k][j++]=a;
}
}
for(i=0;i<k;i++)
{
if(!isoperand(str[i][0]))
{
strcpy(si[f],str[i]);
}
else
{
if(str[i][0]=='(')
{
push(&s,str[i][0]);
}
else if(str[i][0]==')')
{
while(!empty(&s))
{
char t = pop(&s);
if(t=='(')
break;
else
si[f][0]=t;
}
}
else
{
while(!empty(&s)&&prcd(s.A[s.top],str[i][0]))
{
char t = pop(&s);
if(t=='(')
continue;
si[f++][0]=t;
}
push(&s,str[i][0]);
}
}
}
while(!empty(&s))
{
si[f++][0]=pop(&s);
}
for(i=0;i<f;i++)
{
printf("%s ",si[i]);
}
printf("\n");
}
return 0;
}