File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
src/main/java/com/thealgorithms/stacks Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .Stack ;
2+
3+ public class InfixToPostfix {
4+
5+ // Function to check operator precedence
6+ static int precedence (char ch ) {
7+ switch (ch ) {
8+ case '+' :
9+ case '-' :
10+ return 1 ;
11+ case '*' :
12+ case '/' :
13+ return 2 ;
14+ case '^' :
15+ return 3 ;
16+ }
17+ return -1 ;
18+ }
19+
20+ // Function to convert infix to postfix
21+ static String convert (String expression ) {
22+ String result = "" ;
23+ Stack <Character > stack = new Stack <>();
24+
25+ for (int i = 0 ; i < expression .length (); i ++) {
26+ char c = expression .charAt (i );
27+
28+ // If character is an operand, add it to output
29+ if (Character .isLetterOrDigit (c )) {
30+ result += c ;
31+ }
32+
33+ // If character is '(', push it to stack
34+ else if (c == '(' ) {
35+ stack .push (c );
36+ }
37+
38+ // If character is ')', pop until '(' is found
39+ else if (c == ')' ) {
40+ while (!stack .isEmpty () && stack .peek () != '(' ) {
41+ result += stack .pop ();
42+ }
43+ stack .pop (); // remove '('
44+ }
45+
46+ // If character is operator
47+ else {
48+ while (!stack .isEmpty () && precedence (c ) <= precedence (stack .peek ())) {
49+ result += stack .pop ();
50+ }
51+ stack .push (c );
52+ }
53+ }
54+
55+ // Pop all remaining operators from stack
56+ while (!stack .isEmpty ()) {
57+ result += stack .pop ();
58+ }
59+
60+ return result ;
61+ }
62+
63+ // Main method to test the program
64+ public static void main (String [] args ) {
65+ String infix = "A*(B+C)/D" ;
66+ System .out .println ("Infix: " + infix );
67+ System .out .println ("Postfix: " + convert (infix ));
68+ }
69+ }
You can’t perform that action at this time.
0 commit comments