-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix to prefix.c
67 lines (67 loc) · 1.4 KB
/
infix to prefix.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
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
int precedence(char op);
int isoperator(char op);
void main()
{
char infix[100],prefix[100],stack[100];
int i,j=0,top=-1;
printf("Enter the infix expression in paranthesis\n");
gets(infix);
for(i=strlen(infix)-1;i>=0;i--)
{
if(infix[i]==')')
stack[++top]=')';
else if(isalpha(infix[i]))
prefix[j++]=infix[i];
else if(infix[i]=='(')
{
while(stack[top]!=')')
{
prefix[j++]=stack[top--];
}
top--; // to remove the right paranthesis
}
else if(isoperator(infix[i]))
{
while(precedence(stack[top])>precedence(infix[i]))
{
prefix[j++]=stack[top--];
}
stack[++top]=infix[i];
}
else
{
printf("Invalid symbol");
getch();
exit(1);
}
}
prefix[j]='\0';
strrev(prefix);// to reverse the expression
printf("The converted prefix expression\n");
printf("%s",prefix);
getch();
}
int precedence(char op)
{
if(op=='^')
return 3;
else if(op=='*'||op=='/'||op=='%')
return 2;
else if(op=='+'||op=='-')
return 1;
else
return 0;
}
int isoperator(char op)
{
if(op=='^'||op=='+'||op=='-'||op=='/'||op=='*'
||op=='%')
return 1;
else
return 0;
}