-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathInfixToPostfix in c
More file actions
82 lines (69 loc) · 1.54 KB
/
InfixToPostfix in c
File metadata and controls
82 lines (69 loc) · 1.54 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
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char c) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = c;
}
char pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int precedence(char op) {
if (op == '^')
return 3;
if (op == '*' || op == '/')
return 2;
if (op == '+' || op == '-')
return 1;
return 0;
}
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
void infixToPostfix(char infix[]) {
char postfix[MAX];
int j = 0;
for (int i = 0; i < strlen(infix); i++) {
char c = infix[i];
if (isalnum(c)) {
postfix[j++] = c;
}
else if (c == '(') {
push(c);
}
else if (c == ')') {
while (top != -1 && stack[top] != '(') {
postfix[j++] = pop();
}
pop(); // remove '('
}
else if (isOperator(c)) {
while (top != -1 && precedence(stack[top]) >= precedence(c)) {
postfix[j++] = pop();
}
push(c);
}
}
while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0';
printf("Postfix Expression: %s\n", postfix);
}
int main() {
char infix[MAX];
printf("Enter an infix expression: ");
scanf("%s", infix);
infixToPostfix(infix);
return 0;
}