-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix_to_postfix.c
110 lines (93 loc) · 1.95 KB
/
infix_to_postfix.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
struct stack {
char data[N];
int top;
};
void initStack(struct stack *s) {
s->top = -1;
}
int isEmpty(struct stack *s) {
return s->top == -1;
}
int isFull(struct stack *s) {
return s->top == N - 1;
}
void push(struct stack *s, char c) {
if (isFull(s)) {
printf("Stack Overflow \n");
exit(1);
}
s->top++;
s->data[s->top] = c;
}
char pop(struct stack *s) {
if (isEmpty(s)) {
printf("Stack is empty \n");
exit(1);
}
return s->data[(s->top)--];
}
char peek(struct stack *s) {
if (isEmpty(s)) {
return '\0';
}
return s->data[s->top];
}
int precedence(char c) {
switch(c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
int isAlphanumeric(char c) {
return ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9'));
}
void infixToPostfix(char *infix, char *postfix) {
struct stack *s;
initStack(s);
int j=0;
for (int i = 0; infix[i] != '\0'; i++) {
char c = infix[i];
if (isAlphanumeric(c)) {
postfix[j++] = c;
}
else if (c == '(') {
push(s, c);
}
else if (c == ')') {
while (!isEmpty(s) && peek(s) != '(') {
postfix[j++] = pop(s);
}
pop(s);
}
else {
while (!isEmpty(s) && precedence(peek(s)) >= precedence(c)) {
postfix[j++] = pop(s);
}
push(s, c);
}
}
while (!isEmpty(s)) {
postfix[j++] = pop(s);
}
postfix[j] = '\0';
}
int main () {
char infix[N], postfix[N];
printf("Enter the infix expression: ");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s \n", postfix);
return 0;
}