forked from sanjaysunil34/hacktober2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-InfixToPostfix.c
More file actions
86 lines (78 loc) · 1.69 KB
/
6-InfixToPostfix.c
File metadata and controls
86 lines (78 loc) · 1.69 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
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include<ctype.h>
typedef struct {
/* Declare your stack here */
char arr[40];
} Stack;
Stack s;
int top = -1;
void push(char ch) {
s.arr[++top] = ch;
}
char pop() {
char temp;
temp = s.arr[top--];
return temp;
}
int is_operator(char ch) {
if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
return 1;
else
return 0;
}
int precedence(char ch) {
if(ch == '/' || ch == '*')
return 2;
else if(ch == '+' || ch == '-')
return 1;
else
return 0;
}
void infoxToPostfix(char infix[], char postfix[]) {
int i = 0, j = 0;
char x,item;
push('(');
strcat(infix, ")");
item = infix[i];
while (item != '\0') {
if(item == '(') {
push(item);
}
else if(isdigit(item) || isalpha(item)) {
postfix[j++] = item;
}
else if(is_operator(item)) {
x = pop();
while(is_operator(x) && precedence(x) >= precedence(item)) {
postfix[j++] = x;
x = pop();
}
push(x);
push(item);
}
else if(item == ')') {
x = pop();
while (x != '(') {
postfix[j++] = x;
x = pop();
}
}
i++;
item = infix[i];
}
postfix[j] = '\0';
printf("%s",postfix);
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
char infix[100], postfix[100];
int size;
scanf("%d",&size);
scanf("%s",infix);
infoxToPostfix(infix, postfix);
return 0;
}