forked from dscgecbsp/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixtoPostfix.c
101 lines (83 loc) · 1.97 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
/*Infix to Postfix conversation is a code that converts the normal expression to Postfix(Operand first than Operator) And This is an Application of Stack*/
#include<stdio.h>
#include<stdlib.h>
#define N 20
int top=-1;
int push(char s[],char c)
{
if(top <= (N-1))
s[++top]=c;
else
printf("StackOverflow");
return 0;
}
char pop(char s[]){
if(top > (-1))
return (s[top--]);
else
printf("StackUnderflow");
}
char read(char s[]){
if(top >= 0)
return(s[top]);
}
int prec(char ch){
if(ch=='^' || ch=='%') return 3;
else if(ch=='*' || ch=='/') return 2;
else if(ch=='+' || ch=='-') return 1;
}
int isoperand(char c){
if((c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9'))
return 1;
else
return 0;
}
void infixtopostfix(char infix[]){
char s[N];
char postfix[N]={0};
int i=0,p=0;
while(infix[i]!='\0'){
if(isoperand(infix[i])){
postfix[p]=infix[i];
p++;
i++;
}
else if(infix[i]=='('){
push(s,infix[i]);
i++;
}
else if(infix[i]==')'){
while(read(s)!='('){
postfix[p++]=pop(s);
}
pop(s);
i++;
}
else{
if(top==-1 || read(s)=='('){
push(s,infix[i++]);
}
else if(prec(infix[i])>prec(read(s))){
push(s,infix[i]);
i++;
}
else
postfix[p++]=pop(s);
}
}
while(top!=-1)
postfix[p++]=pop(s);
printf("%s ",postfix);
}
int main(){
char infix[20];
printf("Infix expression = ");
scanf("%s",&infix);
printf("Postfix Expression = ");
infixtopostfix(infix);
return 0;
}
/* ""OUTPUT""
Infix expression = a+b*c-d/e*h
Postfix Expression = abc*+de/h*-
*/