Skip to content

Commit 5fd531f

Browse files
authored
Create C(InfixToPostfix) (#3551)
2 parents a1c7621 + f0ccb20 commit 5fd531f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

C(InfixToPostfix)

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <stdio.h>
2+
#include <ctype.h>
3+
#include <string.h>
4+
5+
char stack[100];
6+
int top = -1;
7+
8+
void push(char c) {
9+
stack[++top] = c;
10+
}
11+
12+
char pop() {
13+
return stack[top--];
14+
}
15+
16+
int precedence(char c) {
17+
if (c == '+' || c == '-') return 1;
18+
if (c == '*' || c == '/') return 2;
19+
if (c == '^') return 3;
20+
return 0;
21+
}
22+
23+
void infixToPostfix(char infix[]) {
24+
char postfix[100];
25+
int j = 0;
26+
27+
for (int i = 0; i < strlen(infix); i++) {
28+
char c = infix[i];
29+
30+
// operand
31+
if (isalnum(c)) {
32+
postfix[j++] = c;
33+
}
34+
// left bracket
35+
else if (c == '(') {
36+
push(c);
37+
}
38+
// right bracket
39+
else if (c == ')') {
40+
while (top != -1 && stack[top] != '(') {
41+
postfix[j++] = pop();
42+
}
43+
pop(); // remove '('
44+
}
45+
// operator
46+
else {
47+
while (top != -1 && precedence(c) <= precedence(stack[top])) {
48+
postfix[j++] = pop();
49+
}
50+
push(c);
51+
}
52+
}
53+
54+
// remaining operators
55+
while (top != -1) {
56+
postfix[j++] = pop();
57+
}
58+
59+
postfix[j] = '\0';
60+
printf("Postfix: %s", postfix);
61+
}
62+
63+
int main() {
64+
char infix[] = "A+B*(C-D)";
65+
infixToPostfix(infix);
66+
return 0;
67+
}

0 commit comments

Comments
 (0)