-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixprefix.c
More file actions
159 lines (151 loc) · 2.84 KB
/
Copy pathinfixprefix.c
File metadata and controls
159 lines (151 loc) · 2.84 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Stack
{
int top;
int size;
char *arr;
} Stack;
int isEmpty(Stack *s)
{
if (s->top == -1)
return 1;
else
return 0;
}
int push(Stack *s, char val)
{
if (s->top == s->size - 1)
{
return -1;
}
else
{
s->top++;
s->arr[s->top] = val;
}
}
char peek(Stack *s)
{
return s->arr[s->top];
}
char pop(Stack *s)
{
if (s->top == -1)
{
printf("Empty\n");
}
else
{
char a;
a = s->arr[s->top];
s->top--;
return a;
}
}
int pq(char ch)
{
// if (ch == '(' || ch == ')')
// return 4;
if (ch == '^')
return 3;
else if (ch == '*' || ch == '/')
return 2;
else if (ch == '+' || ch == '-')
return 1;
else
return -1;
}
int checkElement(char c)
{
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
return 1;
else
return 2;
}
char *reverse(char *exp)
{
int n = strlen(exp);
char *ans = (char *)malloc(n * sizeof(char));
int i = 0;
while (exp[i] != '\0')
{
ans[n - 1 - i] = exp[i];
i++;
}
ans[n] = '\0';
return ans;
}
char *prefix(char *str, Stack *s)
{
char *ans = (char *)malloc((strlen(str) + 1) * sizeof(char));
int i = 0;
int len = 0;
while (str[i] != '\0')
{
char ch = str[i];
int choice = checkElement(ch);
// printf("%d ", choice);
switch (choice)
{
case 1:
ans[len] = ch;
len++;
i++;
break;
case 2:
if (ch == ')')
{
push(s, ch);
}
else if (s->arr[s->top] == ')')
{
push(s, ch);
}
else if (ch == '(')
{
while (s->arr[s->top] != ')' && !isEmpty(s))
{
ans[len] = pop(s);
len++;
}
pop(s);
}
else
{
while (pq(ch) <= pq(s->arr[s->top]) && !isEmpty(s))
{
ans[len] = pop(s);
len++;
}
push(s, ch);
}
i++;
break;
}
}
while (!isEmpty(s))
{
ans[len] = pop(s);
len++;
}
ans[len] = '\0';
return ans;
}
int main()
{
Stack *s = (Stack *)malloc(sizeof(Stack));
s->top = -1;
s->size = 100;
s->arr = (char *)malloc(s->size * sizeof(char));
// char *str = "(P+(Q*R)/(S-T))";
char str[100];
gets(str);
//+P/*QR-ST
char *exp = reverse(str);
// printf("%s", exp);
char *ans = prefix(exp, s);
ans = reverse(ans);
printf("\n%s",ans);
}