forked from rexxyz/language-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infix_to_postfix.c
136 lines (130 loc) · 2.66 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
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
126
127
128
129
130
131
132
133
134
135
136
#include<stdio.h>
#include<string.h>
#define SIZE 20
enum precedence{lparen, rparen, plus, minus ,times ,divide ,mod , operand};
int stack[SIZE];
char EXP[SIZE];
char string[SIZE];//The expression is also made global.
int TOP =-1;
void push (int c);
int pop (void);
void printToken(void);
int getToken(char c);
void postfix(int token);
int main()
{
int token,temp1,temp2,spare;
postfix(lparen);
printf("%d",stack[TOP]);
printf("please enter the expression\n");
scanf("%s",string);
for (int i = 0; string[i]!='\0'; ++i)
{
token=getToken(string[i]);
if(token==operand)
{printf("%c",string[i]);continue;}
postfix(token);
}
postfix(rparen);
printf("\n");
printf("please enter the expression you want to evaluate\n");
scanf("%s",EXP);
for (int i = 0; EXP[i]!='\0'; ++i)
{
token=getToken(EXP[i]);
if (token==operand)
{
spare =(int)EXP[i]-48;
push(spare);
}
else
{
temp1=pop();
temp2=pop();
switch(token)
{
case plus:push(temp2+temp1);break;
case minus:push(temp2-temp1);break;
case mod:push(temp2%temp1);break;
case times:push(temp2*temp1);break;
case divide:push(temp2/temp1);break;
}
}
}
printf("%d\n",pop() );
return 0;
}
void push (int c)
{
if(TOP==SIZE-1)
{
printf("stack overflow\n");
}
else
{
TOP++;
stack[TOP]=c;
}
}
int pop(void)
{ int temp;
if(TOP==-1)
{
printf("stack underflow\n");
return 0;
}
else
{
temp=stack[TOP];
TOP--;
return temp;
}
}
void postfix(int token)
{ int i;
int in_stack_precedence[]={0,19,12,12,13,13,13};
int incoming_precedence[]={20,19,12,12,13,13,13};
if (token==rparen)
{
while(stack[TOP]!=lparen){printToken();}
pop();
return ;//poping the left braces.
}
if(in_stack_precedence[stack[TOP]]<incoming_precedence[token]&&(token!=rparen))
{
push(token);return;
}
if(in_stack_precedence[stack[TOP]]>=incoming_precedence[token])
{
while(in_stack_precedence[stack[TOP]]>=incoming_precedence[token])
{printToken();}
push(token);
}
}
int getToken(char character)
{
switch(character)
{
case '(':return lparen;
case ')':return rparen;
case '+':return plus;
case '-':return minus;
case '/':return divide;
case '*':return times;
case '%':return mod;
default :return operand;
}
}
void printToken(void)
{
int temp;
temp=pop();
switch(temp)
{ case plus:printf("+");break;
case minus:printf("-");break;
case divide:printf("/");break;
case times:printf("*");break;
case mod:printf("%");break;
// Pull by Mabizarnovaris
}
}