-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prefix_evaluation.cpp
50 lines (49 loc) · 1009 Bytes
/
Prefix_evaluation.cpp
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
#include <iostream>
#include<stack>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
int postfix_eval(char[]);
using namespace std;
int main()
{
char a[20];
cout <<"Enter Prefix Expression::";
gets(a);
cout<<"Result::"<<postfix_eval(a);
return 0;
}
int postfix_eval(char a[])
{
stack<int>s;
for(int i=strlen(a)-1;i>=0;i--)
{
int num=0;
if(isdigit(a[i]))
{
while(a[i]!=' ')
{
num=10*num+(a[i]-'0');
i--;
}
s.push(num);
}
if(a[i]=='*'||a[i]=='+'||a[i]=='-'||a[i]=='/')
{
char b,c;
c=s.top();
s.pop();
b=s.top();
s.pop();
if(a[i]=='*')
s.push(b*c);
if(a[i]=='/')
s.push(c/b);
if(a[i]=='-')
s.push(c-b);
if(a[i]=='+')
s.push(b+c);
}
}
return s.top();
}