-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixtopostfix.c
More file actions
125 lines (74 loc) · 1.7 KB
/
Copy pathinfixtopostfix.c
File metadata and controls
125 lines (74 loc) · 1.7 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
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<ctype.h>
typedef struct Stack{
int size;
int top;
char *arr;
}Stack;
Stack* createStack(int size){
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->size = size;
stack->top = -1;
stack->arr = (char*)malloc(sizeof(char)*size);
return stack;
}
void push(int val,Stack* stack){
stack->arr[++stack->top] = val;
}
char pop(Stack* stack){
return stack->arr[stack->top--];
}
int isEmpty(Stack* stack){
return stack->top == -1;
}
void peek(Stack* stack){
printf("%c ", stack->arr[stack->top]);
}
int precedence(char ch){
if(ch == '*' || ch == '/') return 2;
if(ch == '+' || ch == '-') return 1;
else return 0;
}
int isComparator(char ch){
if(ch == '*' || ch == '/' || ch == '+' || ch == '-') return 1;
else return 0;
}
void infixToPostfix(char infix[],char postfix[]){
Stack* stack = createStack(100);
int i = 0;
int j = 0;
while(infix[i] != '\0'){
char ch = infix[i];
if(isalnum(ch)){
postfix[j++] = ch;
}
else if(ch == '('){
stack->arr[++stack->top] = ch;
}
else if(ch == ')'){
while(stack->top != -1 && stack->arr[stack->top] != '('){
postfix[j++] = pop(stack);
}
stack->top--;
}
else if(isComparator(ch)){
while(stack->top == -1 && precedence(stack->arr[stack->top]) >= precedence(ch)){
postfix[j++] = pop(stack);
}
stack->arr[++stack->top] = ch;
}
i++;
}
while(stack->top != -1){
postfix[j++] = pop(stack);
}
postfix[j] = '\0';
printf("%s",postfix);
}
int main(){
char infix[] = "(a+b)*(c-d)";
char postfix[] = "";
infixToPostfix(infix,postfix);
}