-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix.c
63 lines (54 loc) · 1.16 KB
/
infix.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
#include <stdio.h>
#include <string.h>
char Stack[1024];
int sp;
char Infix[255];
char Postfix[255];
char push(char c) { Stack[sp++] = c; return c; }
char pop (void) { return Stack[--sp]; }
char top(void) { return Stack[sp-1]; }
int empty(void) { return sp == 0; }
int prty(int c) {
int p;
if(c == '(' || c == ')') return 0;
else if(c == '+' || c == '-') return 1;
else if(c == '*' || c == '/') return 2;
else return -1;
}
void infix2postfix(char* Infix, char* Postfix) {
char c;
sp = 0;
while(c = *Infix++) {
switch(c) {
case '(' :
push(c);
break;
case ')' :
while(top() != '(') *Postfix++ = pop();
pop();
break;
case '+' :
case '-' :
case '*' :
case '/' :
while(prty(c) <= prty(top()))
*Postfix++ = pop();
push(c);
break;
default :
*Postfix++ = c;
break;
}
}
while(!empty()) *Postfix++ = pop();
*Postfix = '\0';
}
void main() {
while(1) {
printf("Enter Infix Espression:> ");
fgets(Infix, sizeof(Infix), stdin);
Infix[strlen(Infix)-1] = '\0'; // skip \n
infix2postfix(Infix, Postfix);
printf("PostFix Form: %s\n", Postfix);
}
}