-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathC(InfixToPostfix)
More file actions
67 lines (57 loc) · 1.25 KB
/
C(InfixToPostfix)
File metadata and controls
67 lines (57 loc) · 1.25 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
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char stack[100];
int top = -1;
void push(char c) {
stack[++top] = c;
}
char pop() {
return stack[top--];
}
int precedence(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
if (c == '^') return 3;
return 0;
}
void infixToPostfix(char infix[]) {
char postfix[100];
int j = 0;
for (int i = 0; i < strlen(infix); i++) {
char c = infix[i];
// operand
if (isalnum(c)) {
postfix[j++] = c;
}
// left bracket
else if (c == '(') {
push(c);
}
// right bracket
else if (c == ')') {
while (top != -1 && stack[top] != '(') {
postfix[j++] = pop();
}
pop(); // remove '('
}
// operator
else {
while (top != -1 && precedence(c) <= precedence(stack[top])) {
postfix[j++] = pop();
}
push(c);
}
}
// remaining operators
while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0';
printf("Postfix: %s", postfix);
}
int main() {
char infix[] = "A+B*(C-D)";
infixToPostfix(infix);
return 0;
}