-
Notifications
You must be signed in to change notification settings - Fork 0
/
reversePolishNotation.cpp
109 lines (105 loc) · 2.22 KB
/
reversePolishNotation.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
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
/*
* Reverse Polish Notation:
* https://en.wikipedia.org/wiki/Reverse_Polish_notation
*/
/*
* In this code function rpn_calculate() takes the input of tokens
* and calculates the value.
* Whenever it finds '+', '-', '*', and '/' it pops two values from
* list and perform the reqd. operation.
* Here list 'stack' acts as a stack.
* All the inputs are integers but result can be float as division
* is involved.
* If the input is wrong the funtion prints error and returns -1.
*/
#include <list>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
float rpn_calculate(vector < string > tokens) {
list<float> stack;
for (string var : tokens)
{
if(var == "+")
{
if (stack.size()<2) {
cout<<"Error in input"<<endl;
return -1;
}
float no1 = stack.front();
stack.pop_front();
float no2 = stack.front();
stack.pop_front();
float temp = no2 + no1;
stack.push_front(temp);
}
else if(var == "-")
{
if (stack.size()<2) {
cout<<"Error in input"<<endl;
return -1;
}
float no1 = stack.front();
stack.pop_front();
float no2 = stack.front();
stack.pop_front();
float temp = no2 - no1;
stack.push_front(temp);
}
else if(var == "*")
{
if (stack.size()<2) {
cout<<"Error in input"<<endl;
return -1;
}
float no1 = stack.front();
stack.pop_front();
float no2 = stack.front();
stack.pop_front();
float temp = no2 * no1;
stack.push_front(temp);
}
else if(var == "/")
{
if (stack.size()<2) {
cout<<"Error in input"<<endl;
return -1;
}
float no1 = stack.front();
stack.pop_front();
float no2 = stack.front();
stack.pop_front();
float temp = no2 / no1;
stack.push_front(temp);
}
else
{
float temp;
istringstream(var) >> temp;
stack.push_front(temp);
}
}
if (stack.size()!=1) {
cout<<"Error in input"<<endl;
return -1;
}
return stack.front();
}
int main(int argc, char* argv[])
{
vector<string> str;
str.push_back("5");
str.push_back("1");
str.push_back("2");
str.push_back("+");
str.push_back("4");
str.push_back("*");
str.push_back("+");
str.push_back("3");
str.push_back("-");
float res = rpn_calculate(str);
cout << "result is: "<<res<<endl;
return 0;
}