-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinfixToPrefix.c
112 lines (94 loc) · 1.72 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
// Infix to Prefix
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define CAPACITY 50
char stack[CAPACITY];
int top = -1;
bool isEmpty()
{
if (top == -1)
{
return true;
}
return false;
}
void push(char data)
{
stack[++top] = data;
}
char pop()
{
return stack[top--];
}
char peek()
{
return stack[top];
}
int priority(char x)
{
if (x == '+' || x == '-')
return 1;
else if (x == '*' || x == '/')
return 2;
else if (x == '^')
return 3;
else
return 0;
}
void main()
{
char input[CAPACITY];
char output[CAPACITY];
printf("Enter the Expression : ");
scanf("%s", input);
strrev(input);
int j = 0;
while (input[j] != '\0')
{
if (input[j] == '(')
{
input[j] = ')';
}
else if (input[j] == ')')
{
input[j] = '(';
}
j++;
}
int i = 0, k = 0;
while (input[i] != '\0')
{
if (input[i] == '(')
{
push(input[i]);
}
else
{
if (input[i] >= 'A' && input[i] <= 'Z')
{
output[k++] = input[i];
}
else if (input[i] == ')')
{
while (peek() != '(')
{
output[k++] = pop();
}
pop();
}
else
{
while (priority(input[i]) <= priority(peek()))
{
output[k++] = pop();
}
push(input[i]);
}
}
i++;
}
output[k++] = '\0';
strrev(output);
printf(" Prefix Expression : %s", output);
}