1+ #include < iostream>
2+ #include < string>
3+
4+ using namespace std ;
5+
6+ const int MAX_SIZE = 100 ;
7+
8+ struct Stack {
9+ int top; // index of top of stack
10+ string elements[MAX_SIZE];
11+ };
12+
13+ bool isEmpty (Stack& stack) {
14+ return stack.top == -1 ;
15+ }
16+
17+ bool isFull (Stack& stack) {
18+ return stack.top == MAX_SIZE - 1 ;
19+ }
20+
21+ void push (Stack& stack, string value) {
22+ if (isFull (stack)) {
23+ cout << " Stack overflow!" << endl;
24+ return ;
25+ }
26+ stack.elements [++stack.top ] = value;
27+ }
28+
29+ void pop (Stack& stack) {
30+ if (isEmpty (stack)) {
31+ cout << " Stack underflow!" << endl;
32+ return ;
33+ }
34+ stack.elements [stack.top --] = " " ;
35+ }
36+
37+ string top (Stack& stack) {
38+ if (isEmpty (stack)) {
39+ return " " ;
40+ }
41+ return stack.elements [stack.top ];
42+ }
43+
44+ string removeSpaces (string str) {
45+ string result;
46+ for (int i = 0 ; i < str.size () ; i++) {
47+ if (str[i] != ' ' ) {
48+ result += str[i];
49+ }
50+ }
51+ return result;
52+ }
53+
54+ void postfix (Stack& stack, string phrase) {
55+ for (int i = 0 ; i < phrase.size (); i++) {
56+ string p = string (1 , phrase[i]);
57+ if (p >= " 0" && p <= " 9" || p >= " a" && p <= " z" ) {
58+ string number;
59+ while (p >= " 0" && p <= " 9" || p >= " a" && p <= " z" ) {
60+ number += p;
61+ i++;
62+ if (i < phrase.size ()) {
63+ p = string (1 , phrase[i]);
64+ } else {
65+ break ;
66+ }
67+ }
68+ i--;
69+ cout << number << " " ;
70+ } else if (p == " (" || p == " )" || p == " {" || p == " }" || p == " [" || p == " ]" ) {
71+ push (stack, p);
72+ } else {
73+ while (true ) {
74+ if (isEmpty (stack) || top (stack) == " (" || top (stack) == " [" || top (stack) == " {" ) {
75+ push (stack, p);
76+ break ;
77+ } else if (top (stack) == " +" || top (stack) == " -" || top (stack) == " /" ||
78+ top (stack) == " *" ) {
79+ if ((p == " *" || p == " /" ) && (top (stack) == " -" || top (stack) == " +" )) {
80+ push (stack, p);
81+ break ;
82+ } else {
83+ if (top (stack) != " (" && top (stack) != " )" && top (stack) != " {" &&
84+ top (stack) != " }" && top (stack) != " [" && top (stack) != " ]" ) {
85+ cout << top (stack) << " " ;
86+ }
87+ pop (stack);
88+ }
89+ } else {
90+ break ;
91+ }
92+ }
93+ }
94+ }
95+ while (!isEmpty (stack)) {
96+ string p = top (stack);
97+ if (p != " (" && p != " )" && p != " {" && p != " }" && p != " [" && p != " ]" ) {
98+ cout << p << " " ;
99+ }
100+ pop (stack);
101+ }
102+ }
103+
104+ int main () {
105+ Stack stack;
106+ stack.top = -1 ;
107+ string str;
108+ cout << " Enter the phrase: " ;
109+ getline (cin,str);
110+ postfix (stack, removeSpaces (str));
111+
112+ return 0 ;
113+ }
114+
115+ /*
116+ Reza Asadi (Github : RezaGooner)
117+ 1402/08/22 ~ 2023/11/13
118+ */
0 commit comments