-
Notifications
You must be signed in to change notification settings - Fork 0
/
4. Infix-to-Postfix.c
87 lines (75 loc) · 1.63 KB
/
4. Infix-to-Postfix.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
#include<stdio.h>
#include<string.h>
char infix[20],postfix[20],stack[20];
int top=-1;
int isEmpty(){
if(top<0)
return 1;
else
return 0;
}
void push(char symbol){
++top;
stack[top]=symbol;
return;
}
int pop(){
int temp=stack[top];
--top;
return temp;
}
int precedence(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default: return 0;
break;
}
}
void infix_postfix(char*infix,char*postfix){
int i,j=0;
char symbol,next;
for(i=0;i<strlen(infix);i++){
symbol=infix[i];
switch(symbol)
{
case '(':push(symbol);
break;
case ')':while((next=pop())!='(')
postfix[j++]=next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':while(!isEmpty()&&precedence(stack[top])>=precedence(symbol))
postfix[j++]=pop();
push(symbol);
break;
default:postfix[j++]=symbol;
break;
}
}
while(!isEmpty()){
postfix[j++]=pop();
}
postfix[j]='\0';
}
int main(){
printf("Enter a valid infix expression:");
scanf("%s",infix);
infix_postfix(infix,postfix);
printf("The Infix expression is:%s\n",infix);
printf("The Postfix expression is:%s",postfix);
return 0;
}