-
Notifications
You must be signed in to change notification settings - Fork 10
/
postfix_to_prefix.c
87 lines (72 loc) · 1.19 KB
/
postfix_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
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>
#include<stdlib.h>
#define MAX 20
char str[MAX], stack[MAX];
int top = -1;
void push(char c)
{
stack[++top] = c;
}
char pop()
{
return stack[top--];
}
// A utility function to check if the given character is operand
int checkIfOperand(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
//function to check if it is an operator
int isOperator(char x)
{
switch (x) {
case '+':
case '-':
case '/':
case '*':
return 1;
}
return 0;
}
void postfixToprfix()
{
int n, i, j = 0;
char c[20];
char a, b, op;
printf("Enter the postfix expression\n");
scanf("%s", str);
n = strlen(str);
for (i = 0; i < MAX; i++)
stack[i] = '\0';
printf("Prefix expression is:\t");
for (i = n - 1; i >= 0; i--)
{
if (isOperator(str[i]))
{
push(str[i]);
} else
{
c[j++] = str[i];
while ((top != -1) && (stack[top] == '#'))
{
a = pop();
c[j++] = pop();
}
push('#');
}
}
c[j] = '\0';
i = 0;
j = strlen(c) - 1;
char d[20];
while (c[i] != '\0') {
d[j--] = c[i++];
}
printf("%s\n", d);
}
int main()
{
postfixToprfix();
return 0;
}