File tree Expand file tree Collapse file tree 1 file changed +98
-0
lines changed Expand file tree Collapse file tree 1 file changed +98
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* C++ implementation to convert infix expression to postfix, system takes infix expression from the user as an input */
2
+
3
+ #include < bits/stdc++.h>
4
+ #include < stack>
5
+ #include < string>
6
+ using namespace std ;
7
+
8
+ // Function to return precedence of operators
9
+ int prec (char c)
10
+ {
11
+ if (c == ' $' )
12
+ return 4 ;
13
+ else if (c == ' ^' )
14
+ return 3 ;
15
+ else if (c == ' *' || c == ' /' )
16
+ return 2 ;
17
+ else if (c == ' +' || c == ' -' )
18
+ return 1 ;
19
+ else
20
+ return -1 ;
21
+ }
22
+
23
+ // The main function to convert infix expression
24
+ // to postfix expression
25
+ void infixToPostfix (string s)
26
+ {
27
+ stack<char > st;
28
+ st.push (' N' );
29
+ int l = s.length ();
30
+ string ns;
31
+ for (int i = 0 ; i < l; i++)
32
+ {
33
+ // If the scanned character is an operand, add it to output string.
34
+ if ((s[i] >= ' a' && s[i] <= ' z' )||(s[i] >= ' A' && s[i] <= ' Z' ))
35
+ ns+=s[i];
36
+
37
+ // If the scanned character is an ‘(‘, push it to the stack.
38
+ else if (s[i] == ' (' )
39
+
40
+ st.push (' (' );
41
+
42
+ // If the scanned character is an ‘)’, pop and to output string from the stack
43
+ // until an ‘(‘ is encountered.
44
+ else if (s[i] == ' )' )
45
+ {
46
+ while (st.top () != ' N' && st.top () != ' (' )
47
+ {
48
+ char c = st.top ();
49
+ st.pop ();
50
+ ns += c;
51
+ }
52
+ if (st.top () == ' (' )
53
+ {
54
+ char c = st.top ();
55
+ st.pop ();
56
+ }
57
+ }
58
+
59
+ // If an operator is scanned
60
+ else {
61
+ while (st.top () != ' N' && prec (s[i]) <= prec (st.top ()))
62
+ {
63
+ char c = st.top ();
64
+ st.pop ();
65
+ ns += c;
66
+ }
67
+ st.push (s[i]);
68
+ }
69
+
70
+ }
71
+ // Pop all the remaining elements from the stack
72
+ while (st.top () != ' N' )
73
+ {
74
+ char c = st.top ();
75
+ st.pop ();
76
+ ns += c;
77
+ }
78
+
79
+ cout << ns << endl;
80
+
81
+ }
82
+
83
+ // Driver program to test above functions
84
+ int main ()
85
+ {
86
+
87
+ string exp;
88
+ cout << " Please enter the infix expression you need to convert: \n " ;
89
+ getline (cin,exp);// Get the infrix expression as an input from the user
90
+ /* EXAMPLE OF SOME INFIX EXPRESSIONS :
91
+ a+b
92
+ (a+b)*c
93
+ (A+B)*(C+D)
94
+ */
95
+ infixToPostfix (exp);
96
+ return 0 ;
97
+ }
98
+
You can’t perform that action at this time.
0 commit comments