-
Notifications
You must be signed in to change notification settings - Fork 0
/
infixToPostfix.c
97 lines (88 loc) · 1.84 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
#include <stdio.h>
#include <ctype.h>
struct stack{
char s[20];
int top;
};
int precedence (char ch)
{
switch(ch){
case '^':return(5);break;
case '/':
case '*':return(3);break;
case '+':
case '-':return(1);
default:return(0);
}
}
int push(struct stack *st,char c)
{
st->top+=1;
st->s[st->top]=c;
return(1);
}
int pop(struct stack *st)
{
char temp;
if(st->top==-1)
{
return 0;
}
else
{
temp=st->s[st->top];
st->top-=1;
return(temp);
}
}
int in_to_post(char infix[20], struct stack *st)
{
char postfix[20],symbol;
int i,j=0;
for(i=0;infix[i]!='\0';i++){
symbol=infix[i];
if (isalnum(symbol))
{
postfix[j++]=symbol;
}
else{
switch(symbol){
case('('):push(st,symbol);break;
case(')'):
while(st->s[st->top]!='(')
{
postfix[j++]=pop(st);
}
pop(st);
break;
case('+'):
case('-'):
case('*'):
case('/'):
case('^'):
while(precedence(st->s[st->top])>=precedence(symbol) && st->top!=-1)
{
postfix[j++]=pop(st);
}
push(st,symbol);
break;
}//switch
}//else
}//for
while(st->top!=-1)
{
postfix[j++]=pop(st);
}
postfix[j++]='\0';
printf("postfix expression= %s\n",postfix);
return(1);
}
int main() {
struct stack s;
char infix[20];
s.top=-1;
printf("Enter infix expression: \n");
scanf("%s", infix);
in_to_post(infix,&s);
return 0;
}