forked from ossamamehmood/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfixtoprefix.c
127 lines (126 loc) · 2.75 KB
/
infixtoprefix.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
char st[MAX];
int top = -1;
char pop(char st[]);
void push(char st[], char c);
void infixtopostfix(char source[], char target[]);
int getpriority(char);
char *strrev(char *str)
{
char c, *front, *back;
if(!str || !*str)
return str;
for(front=str,back=str+strlen(str)-1;front < back;front++,back--){
c=*front;*front=*back;*back=c;
}
return str;
}
int main()
{
char infix[100], prefix[100];
printf("\nEnter any infix expression:\n");
gets(infix);
strcpy(prefix, "");
strrev(infix);
for(int i = 0; infix[i] != '\0'; i++)
{
if(infix[i] == '(')
infix[i] = ')';
else if(infix[i] == ')')
infix[i] = '(';
}
puts(infix);
infixtopostfix(infix, prefix);
strrev(prefix);
printf("\nThe corresponding prefix expression is:\n");
puts(prefix);
}
void infixtopostfix(char source[], char target[])
{
int i = 0, j = 0;
char temp;
strcpy(target, "");
while (source[i] != '\0')
{
if (source[i] == '(')
{
push(st, source[i]);
i++;
}
else if (source[i] == ')')
{
while ((top != -1) && (st[top] != '('))
{
target[j] = pop(st);
j++;
}
if (top == -1)
{
printf("\n INCORRECT EXPRESSION");
exit(1);
}
temp = pop(st);
i++;
}
else if (isdigit(source[i]) || isalpha(source[i]))
{
target[j] = source[i];
j++;
i++;
}
else if (source[i] == '+' || source[i] == '-' || source[i] == '*' || source[i] == '/' || source[i] == '%')
{
while ((top != -1) && (st[top] != '(') && (getpriority(st[top]) > getpriority(source[i])))
{
target[j] = pop(st);
j++;
}
push(st, source[i]);
i++;
}
else
{
printf("\nINCORRECT ELEMENT IN THE EXPRESSION");
exit(1);
}
}
while ((top != -1) && (st[top] != '('))
{
target[j] = pop(st);
j++;
}
target[j] = '\0';
}
int getpriority(char op)
{
if (op == '/' || op == '*' || op == '%')
return 1;
else if (op == '+' || op == '-')
return 0;
}
void push(char st[], char val)
{
if (top == (MAX - 1))
printf("\nStack overflow");
else
{
top++;
st[top] = val;
}
}
char pop(char st[])
{
char val = ' ';
if (top == -1)
printf("\nStack underflow");
else
{
val = st[top];
top--;
}
return val;
}