-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathInfix to postfix
101 lines (97 loc) · 1.34 KB
/
Infix to postfix
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
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define size 100
char stack[size];
int top=-1;
void push(char ch)
{
if(top==size-1)
{
printf("stack overflow ");
return ;
}
top++;
stack[top]=ch;
}
char pop()
{
if(top==-1)
{
printf("stack underflow "); exit(0);
}
char item=stack[top];
top--;
return item;
}
int is_operator(char ch)
{
switch(ch)
{
case '+':case'-':case '*': case '/': case '^':case '%' : return 1;
default :return 0;
}
}
int precedence(char ch)
{
if(ch=='^')
return 3;
else if(ch=='*'||ch=='/'||ch=='%')
return 2;
else if(ch=='+'||ch=='-')
return 1;
else
return 0;
}
void infixtopostfix(char infix[],char postfix[])
{
int i=0,j=0;
push('(');
strcat(infix,")");
char item=infix[i];
char ch; while(item!='\0')
{
if(item=='(')
{
push(item);
}
else if(isdigit(item)||isalpha(item))
{
postfix[j]=item;
j++;
}
else if(is_operator(item)==1)
{
ch=pop(); while(is_operator(ch)==1&&precedence(ch)>=precedence(item))
{
postfix[j]=ch;
j++;
ch=pop();
}
push(ch);
push(item);
}
else if(item==')')
{
ch=pop();
while(ch!='(')
{
postfix[j]=ch;
j++;
ch=pop();
}
}
i++;
item=infix[i];
}
postfix[j]='\0';
}
void main()
{
char infix[size],postfix[size];
printf("enter infix : ");
gets(infix);
infixtopostfix(infix,postfix);
printf("post fix : ");
puts(postfix);
}