-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix_prefix.c
108 lines (92 loc) · 1.46 KB
/
infix_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
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct
{
int top;
char stk[50];
}STACK;
void push(STACK *ptr, char el)
{
ptr->stk[++ptr->top] = el;
}
char pop(STACK *ptr)
{
return ptr->stk[ptr->top --];
}
char peek(STACK *ptr)
{
return ptr->stk[ptr->top];
}
int prec(char x)
{
switch(x)
{
case '+':
case '-':
return 0;
case '*':
case '/':
case '%':
return 1;
}
}
void reverse(char *str)
{
char *temp;
int i, k=0;
for(i = strlen(str)-1; i>=0; i--)
{
temp[k++] = str[i];
}
temp[k] = '\0';
strcpy(str, temp);
}
int isEmpty(STACK *ptr)
{
if(ptr->top == -1)
return 1;
else
return 0;
}
int main()
{
STACK *ptr;
ptr = (STACK*)malloc(sizeof(STACK));
ptr->top = -1;
char infix[50], prefix[50];
printf("\nEnter infix expression - \n");
scanf("%s", infix);
int i=0, k=0;
reverse(infix);
while(i!=strlen(infix))
{
if(isalpha(infix[i]))
{
prefix[k++] = infix[i];
}
else if((prec(peek(ptr))<=prec(infix[i]))||isEmpty(ptr)||infix[i] == ')')
push(ptr, infix[i]);
else if(infix[i] == '(')
{
while(peek(ptr)!=')' && !isEmpty(ptr))
prefix[k++] = pop(ptr);
char junk = pop(ptr);
}
else if(prec(peek(ptr))>prec(infix[i]))
{
while(prec(peek(ptr))>prec(infix[i]))
{
prefix[k++] = pop(ptr);
}
push(ptr, infix[i]);
}
i++;
}
while(!isEmpty(ptr))
prefix[k++] = pop(ptr);
prefix[k] = '\0';
reverse(prefix);
printf("\nPrefix - %s\n", prefix);
}