-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfix.cpp
More file actions
103 lines (88 loc) · 1.82 KB
/
Copy pathPostfix.cpp
File metadata and controls
103 lines (88 loc) · 1.82 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
99
100
101
102
#include <iostream>
using namespace std;
int pos;
void evaluate_postfix(string expression);
bool is_digit(char c);
bool is_operator(char c);
void input_stack(int *stack,int digit);
void calculate(int *stack,char operate);
int main()
{
cout <<"Input Postfix Expression as a string : "<< endl;
string expression;
cin >> expression;
evaluate_postfix(expression);
return 0;
}
void evaluate_postfix(string expression)
{
int stack[100];
pos=0;
for(int i=0;expression[i]!='\0';i++)
{
if(is_digit(expression[i]))
{
if(is_digit(expression[i+1]))
{
input_stack(stack,((expression[i]-48)*10)+(expression[i+1]-48));
i++;
}
else
{
input_stack(stack,expression[i]-48);
}
}
else if(is_operator(expression[i]))
{
calculate(stack,expression[i]);
}
}
cout << "Answer : " << stack[0] << endl;
}
bool is_digit(char c)
{
if(c>='0' && c<='9')
return true;
return false;
}
bool is_operator(char c)
{
if(c=='+' || c=='-' || c=='*' || c=='/')
return true;
return false;
}
void input_stack(int *stack,int digit)
{
stack[pos]=digit;
pos++;
for(int i=0;i<pos;i++)
{
cout << stack[i] << " , " ;
}
cout << endl;
}
void calculate(int *stack,char operate)
{
if(operate=='+')
{
stack[pos-2]=stack[pos-2] + stack[pos-1];
}
if(operate=='-')
{
stack[pos-2]=stack[pos-2] - stack[pos-1];
}
if(operate=='*')
{
stack[pos-2]=stack[pos-2] * stack [pos-1];
}
if(operate=='/')
{
stack[pos-2]=stack[pos-2] / stack[pos-1];
}
pos--;
for(int i=0;i<pos;i++)
{
cout << stack[i] << " , " ;
}
cout << endl;
}