-
Notifications
You must be signed in to change notification settings - Fork 0
/
in_postt.c
148 lines (146 loc) · 2.49 KB
/
in_postt.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
137
138
139
140
141
142
143
144
145
146
147
148
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 15
void in_post();
int isfull();
int isempty() ;
void push(int item);
char pop();
int eva_post() ;
int prior(char sym);
int incm_prior(char sym);
int top=-1;
char arr[MAX];
char infix[100], postfix[100];
int main()
{
scanf("%[^\n]s",infix);
in_post();
int i=eva_post();
printf("%d\n",i);
return 0;
}
void in_post(){
int i,p=0,l;
char sym,itm;
for(i = 0; i< strlen(infix); i++){
sym = infix[i];
if(sym == '(')
push (sym);
else if( sym == '^' ||sym == '*' || sym== '/' || sym == '+' || sym== '-' || sym == '%') {
if(isempty())
push (sym);
else{
while (prior(arr[top]) >= incm_prior(sym) && !isempty()) {
itm= pop();
postfix[p++] = itm;
}
push (sym);
}
}
else if (sym == ')'){
while ((itm = pop()) != '('){
postfix[p++] = itm;
}
}
else
postfix[p++] = sym;
}
while(!isempty()) {
itm = pop();
postfix[p++] = itm;
}
postfix[p]='\0';
}
void push(int item){
if(isfull())
printf("stack overflow\n");
else
{
top=top+1;
arr[top]=item;
}
}
int isempty() {
if(top==-1 )
return 1;
return 0;
}
int isfull() {
if(top==( MAX-1) )
return 1;
return 0;
}
char pop()
{
if(isempty() )
return -1;
else{
char in= arr[top];
top=top-1;
return in;
}
}
void view()
{
int i;
if(top==-1)
printf("stack underflow\n");
for(i=0;i<top;i++)
printf("%d ",arr[i]);
}
int prior(char sym){
if(sym == '^') return 3;
else if(sym == '*' || sym== '/'|| sym == '%') return 2;
else if(sym == '+' || sym== '-') return 1;
else
return 0;
}
int incm_prior(char sym){
if(sym == '^') return 4;
else if(sym == '*' || sym== '/'|| sym == '%') return 2;
else if(sym == '+' || sym== '-') return 1;
else
return 0;
}
int eva_post() {
int i,result;
int sym,itm,a,b;
for(i = 0; i< strlen(postfix); i++){
if(postfix[i] >= '0' && postfix[i] <='9')
push(postfix[i]-'0');
else if( postfix[i] == '^' ||postfix[i] == '*' || postfix[i]== '/' || postfix[i] == '+' || postfix[i]== '-' || postfix[i] == '%') {
if(isempty())
printf("no\n");
else {
a=pop();
b=pop();
switch(postfix[i]) {
case '+':
sym = a+b;
break;
case '-':
sym =b-a;
break;
case '*':
sym = a*b;
break;
case '/':
sym = b/a;
break;
case '%':
sym = b%a;
break;
case '^':
sym = pow(b,a);
break;
}
push (sym);
}
}
}
result=pop();
return result;
}