-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostfix.cpp
72 lines (66 loc) · 1.49 KB
/
Postfix.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<string>
using namespace std;
#define MAX 50
int stack[MAX];
int TOP = -1;
void PUSH(int num){
if(TOP==MAX-1){
cout<<"\nOVERFLOW";
}else{
TOP++;
stack[TOP]=num;
}
}
void POP(){
if(TOP==-1){
cout<<"\nUNDERFLOW";
}else{
TOP--;
}
}
int postfixToInfix(string postfix){
int oprator1,oprator2,result;
for(int i=0;i<postfix.length();i++){
if(postfix[i]=='+' || postfix[i]=='-' || postfix[i]=='/' || postfix[i]=='*'){
oprator1 = stack[TOP];
POP();
oprator2 = stack[TOP];
POP();
switch (postfix[i])
{
case '+':{
result=oprator2+oprator1;
PUSH(result);
}break;
case '-':{
result=oprator2-oprator1;
PUSH(result);
}break;
case '/':{
result=oprator2/oprator1;
PUSH(result);
}break;
case '*':{
result=oprator2*oprator1;
PUSH(result);
}break;
default:{
cout<<"\nINVALID OPRATOR DETACTED!!!";
}
break;
}
}else{
PUSH(postfix[i]-'0');
}
}
return stack[TOP];
}
int main(){
string postfix;
cout<<"Enter the postfix expression: ";
cin>>postfix;
int result=postfixToInfix(postfix);
cout<<"\nRESULT: "<<result;
return 0;
}