-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinfix to postfix.c
93 lines (85 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
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include "stacklladt.h"
bool isoperator(char token)
{
switch(token)
{
case '+':
case '-':
case '*':
case '/':
case '^':
return true;
}
return false;
}
int priority(char token)
{
if(token=='^')
return 3;
else if(token=='*' || token=='/')
return 2;
else if(token=='+' || token=='-')
return 1;
return 0;
}
int main()
{
STACK *ph;
char postfix[25], token;
char *pt;
int i = 0;
ph = creatstack();
printf("Enter the infix expression\n");
while((token = getchar()) != '0')
{
if(token == '(')
{
pt=(char*)malloc(sizeof(char));
*pt=token;
pushstack(ph,pt);
}
else if(token == ')')
{
pt = (char*)popstack(ph);
while(*pt != '(')
{
postfix[i++] = *pt;
free(pt);
pt = (char*)popstack(ph);
}
free(pt); // Free the '(' character
}
else if(isoperator(token))
{
pt = (char*)stacktop(ph);
while(!emptystack(ph) && priority(token) <= priority(*pt))
{
pt = (char*)popstack(ph);
postfix[i++] = *pt;
free(pt);
pt = (char*)stacktop(ph);
}
pt = (char*)malloc(sizeof(char));
*pt = token;
pushstack(ph, (void*)pt);
}
else
{
postfix[i++] = token;
}
}
// Pop any remaining operators from the stack
while(!emptystack(ph))
{
pt = (char*)popstack(ph);
postfix[i++] = *pt;
free(pt);
}
postfix[i] = '\0';
printf("Postfix expression: %s", postfix);
destorystack(ph);
return 0;
}