-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.cpp
More file actions
98 lines (71 loc) · 1.53 KB
/
postfix.cpp
File metadata and controls
98 lines (71 loc) · 1.53 KB
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
#include <iostream>
#include <string.h>
#include <bits/stdc++.h>
using namespace std;
bool isoperator(string com)
{
if(com == "+" || com == "-" || com == "*" || com == "/" )
return true;
else
return false;
}
int perform_operation(char operation, int operand1, int operand2)
{
if(operation == '+') return operand1 +operand2;
else if(operation == '-') return operand1 - operand2;
else if(operation == '*') return operand1 * operand2;
else if(operation == '/') return operand1 / operand2;
else cout<<"Unexpected Error \n";
return -1;
}
void rator_operation(stack<int> &box, string str)
{
if(box.size() > 1)
{
int a = box.top();
box.pop();
int b = box.top();
box.pop();
box.push(perform_operation(str[0],b,a)); }
else if(box.size() == 1)
{
if(str[0] == '-')
{
int temp = box.top();
temp = 0-temp;
box.pop();
box.push(temp);
return;
}
}
else
{
cout << "Error" << endl;
}
}
int main()
{
string k;
getline(cin, k);
char arr[k.length()+1];
for(int i = 0; i < k.length()+1; i++)
arr[i] = k[i];
char *str;
str = strtok (arr," ");
stack<int> box;
while(str != NULL)
{
if(isoperator(str))
{
// cout << str << "str condition"<< endl;
rator_operation(box,str);
}
else
{
int k = atoi(str);
box.push(k);
}
str = strtok(NULL, " ");
}
cout << box.top();
}