-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixPostfix.c
More file actions
135 lines (108 loc) · 2.83 KB
/
InfixPostfix.c
File metadata and controls
135 lines (108 loc) · 2.83 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
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char c) {
stack[++top] = c;
}
char pop() {
if (top == -1) {
return '\0';
}
return stack[top--];
}
char peek() {
if (top == -1) {
return '\0';
}
return stack[top];
}
int precedence(char c) {
if (c == '^') return 3;
if (c == '*' || c == '/') return 2;
if (c == '+' || c == '-') return 1;
return 0;
}
int isOperator(char c) {
return (c == '^' || c == '*' || c == '/' || c == '+' || c == '-');
}
void infixtopostfix(char infix[], char postfix[]) {
int i = 0, j = 0;
char c;
while ((c = infix[i]) != '\0') {
if (isalnum(c)) {
postfix[j++] = c;
} else if (c == '(') {
push(c);
} else if (c == ')') {
while (top != -1 && peek() != '(') {
postfix[j++] = pop();
}
pop();
} else if (isOperator(c)) {
while (top != -1 && isOperator(peek()) && precedence(peek()) >= precedence(c)) {
postfix[j++] = pop();
}
push(c);
}
i++;
}
while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0';
}
int evaluatePostfix(char postfix[]) {
int i = 0;
int operand1, operand2, result;
char c;
top = -1;
while ((c = postfix[i]) != '\0') {
if (isdigit(c)) {
push(c - '0');
} else if (isOperator(c)) {
operand2 = pop();
operand1 = pop();
switch (c) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
case '^':
result = 1;
for (int j = 0; j < operand2; j++) {
result *= operand1;
}
break;
default:
printf("Invalid operator encountered.\n");
return -1;
}
push(result);
}
i++;
}
return pop();
}
int main() {
char infix[MAX], postfix[MAX];
printf("Enter the infix expression: ");
fgets(infix, MAX, stdin);
infix[strcspn(infix, "\n")] = '\0';
infixtopostfix(infix, postfix);
printf("The postfix expression is: %s\n", postfix);
int result = evaluatePostfix(postfix);
printf("The result of the postfix evaluation is: %d\n", result);
return 0;
}