forked from VanceKingSaxbeA/MachineLearningAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
P56InfixToPostfix.c
77 lines (67 loc) · 1.79 KB
/
P56InfixToPostfix.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
/*Owner & Copyrights: Vance King Saxbe. A.*/// Program P5.6
#include <stdio.h>
#include <ctype.h>
typedef struct {
char ch;
} StackData;
#include <stack.h>
int main() {
int readConvert(char[]);
void printPostfix(char[], int);
char post[50];
int n = readConvert(post);
printPostfix(post, n);
} //end main
int readConvert(char post[]) {
char getToken(void), token, c;
int precedence(char);
StackData temp;
int h = 0;
Stack S = initStack();
printf("Type an infix expression and press Enter\n");
token = getToken();
while (token != '\n') {
if (isdigit(token)) post[h++] = token;
else if (token == '(') {
temp.ch = token;
push(S, temp);
}
else if (token == ')')
while ((c = pop(S).ch) != '(') post[h++] = c;
else {
while (!empty(S) &&
precedence(peek(S).ch) >= precedence(token))
post[h++] = pop(S).ch;
temp.ch = token;
push(S, temp);
}
token = getToken();
} //end while
while (!empty(S)) post[h++] = pop(S).ch;
return h; //the size of the expression
} //end readConvert
void printPostfix(char post[], int n) {
printf("\nThe postfix form is \n");
for (int h = 0; h < n; h++) printf("%c ", post[h]);
printf("\n");
} //end printPostfix
char getToken() {
char ch;
while ((ch = getchar()) == ' ') ; //empty body
return ch;
} //end getToken
//int precedence(char c) {
// if (c == '(') return 0;
// if (c == '+' || c == '-') return 3;
// if (c == '*' || c == '/') return 5;
//} //end precedence
int precedence(char c) {
switch (c) {
case '(': return 0;
case '+':
case '-': return 3;
case '*':
case '/': return 5;
}//end switch
} //end precedence
/*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/