-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConverting_Infix_Expression_to_Postfix_Expression.c
More file actions
99 lines (80 loc) · 1.99 KB
/
Converting_Infix_Expression_to_Postfix_Expression.c
File metadata and controls
99 lines (80 loc) · 1.99 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
struct Stack {
int top;
char items[MAX_SIZE];
};
typedef struct Stack Stack;
void initialize(Stack* stack) {
stack->top = -1;
}
int isEmpty(Stack* stack) {
return stack->top == -1;
}
int isFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
void push(Stack* stack, char item) {
if (!isFull(stack)) {
stack->items[++stack->top] = item;
}
}
char pop(Stack* stack) {
if (!isEmpty(stack)) {
return stack->items[stack->top--];
}
return '\0';
}
int precedence(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}
}
void infixToPostfix(char* infix, char* postfix) {
Stack stack;
initialize(&stack);
int i = 0, j = 0;
while (infix[i] != '\0') {
char ch = infix[i];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
postfix[j++] = ch;
} else if (ch == '(') {
push(&stack, ch);
} else if (ch == ')') {
while (!isEmpty(&stack) && stack.items[stack.top] != '(') {
postfix[j++] = pop(&stack);
}
pop(&stack);
} else {
while (!isEmpty(&stack) && precedence(ch) <= precedence(stack.items[stack.top])) {
postfix[j++] = pop(&stack);
}
push(&stack, ch);
}
i++;
}
while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}
postfix[j] = '\0';
}
int main() {
char infix[MAX_SIZE];
printf("Enter an infix expression: ");
scanf("%s", infix);
char postfix[MAX_SIZE];
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}