{"id":26813,"date":"2017-12-24T15:24:24","date_gmt":"2017-12-24T09:54:24","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26813"},"modified":"2017-12-24T15:24:24","modified_gmt":"2017-12-24T09:54:24","slug":"java-algorithm-infix-postfix-conversion-using-stack","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-infix-postfix-conversion-using-stack\/","title":{"rendered":"Java Algorithm &#8211; Infix to Postfix Conversion using Stack"},"content":{"rendered":"<p><strong>Infix expression:<\/strong>The expression of the form a op b. When an operator is in-between every pair of operands.<span id=\"more-142798\"><\/span><\/p>\n<p><strong>Postfix expression:<\/strong>The expression of the form a b op. When an operator is followed for every pair of operands.<\/p>\n<p><strong>Why postfix representation of the expression?<\/strong><br \/>\nThe compiler scans the expression either from left to right or from right to left.<\/p>\n<p>Consider the below expression: a op1 b op2 c op3 d<br \/>\nIf op1 = +, op2 = *, op3 = +<\/p>\n<p>The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to add a to it. The result is then added to d after another scan.<\/p>\n<p>The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix) form before evaluation.<\/p>\n<p>The corresponding expression in postfix form is: abc*+d+. The postfix expressions can be evaluated easily using a stack. We will cover postfix expression evaluation in a separate post.<\/p>\n<p><strong>Algorithm<\/strong><br \/>\n<strong>1.<\/strong> Scan the infix expression from left to right.<br \/>\n<strong>2.<\/strong> If the scanned character is an operand, output it.<br \/>\n<strong>3. <\/strong>Else,<br \/>\n\u2026..<strong>3.1<\/strong> If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it.<br \/>\n\u2026..<strong>3.2<\/strong> Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.<br \/>\n<strong>4.<\/strong> If the scanned character is an \u2018(\u2018, push it to the stack.<br \/>\n<strong>5.<\/strong> If the scanned character is an \u2018)\u2019, pop and output from the stack until an \u2018(\u2018 is encountered.<br \/>\n<strong>6.<\/strong> Repeat steps 2-6 until infix expression is scanned.<br \/>\n<strong>7. <\/strong>Pop and output from the stack until it is not empty.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Following is C implementation of the above algorithm<\/p>\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/* Java implementation to convert infix expression to postfix*\/<br\/>\/\/ Note that here we use Stack class for Stack operations<br\/> <br\/>import java.util.Stack;<br\/> <br\/>class Test<br\/>{<br\/>    \/\/ A utility function to return precedence of a given operator<br\/>    \/\/ Higher returned value means higher precedence<br\/>    static int Prec(char ch)<br\/>    {<br\/>        switch (ch)<br\/>        {<br\/>        case &#039;+&#039;:<br\/>        case &#039;-&#039;:<br\/>            return 1;<br\/>      <br\/>        case &#039;*&#039;:<br\/>        case &#039;\/&#039;:<br\/>            return 2;<br\/>      <br\/>        case &#039;^&#039;:<br\/>            return 3;<br\/>        }<br\/>        return -1;<br\/>    }<br\/>      <br\/>    \/\/ The main method that converts given infix expression<br\/>    \/\/ to postfix expression. <br\/>    static String infixToPostfix(String exp)<br\/>    {<br\/>        \/\/ initializing empty String for result<br\/>        String result = new String(&quot;&quot;);<br\/>         <br\/>        \/\/ initializing empty stack<br\/>        Stack&lt;Character&gt; stack = new Stack&lt;&gt;();<br\/>         <br\/>        for (int i = 0; i&lt;exp.length(); ++i)<br\/>        {<br\/>            char c = exp.charAt(i);<br\/>             <br\/>             \/\/ If the scanned character is an operand, add it to output.<br\/>            if (Character.isLetterOrDigit(c))<br\/>                result += c;<br\/>              <br\/>            \/\/ If the scanned character is an &#039;(&#039;, push it to the stack.<br\/>            else if (c == &#039;(&#039;)<br\/>                stack.push(c);<br\/>             <br\/>            \/\/  If the scanned character is an &#039;)&#039;, pop and output from the stack <br\/>            \/\/ until an &#039;(&#039; is encountered.<br\/>            else if (c == &#039;)&#039;)<br\/>            {<br\/>                while (!stack.isEmpty() &amp;&amp; stack.peek() != &#039;(&#039;)<br\/>                    result += stack.pop();<br\/>                 <br\/>                if (!stack.isEmpty() &amp;&amp; stack.peek() != &#039;(&#039;)<br\/>                    return &quot;Invalid Expression&quot;; \/\/ invalid expression                <br\/>                else<br\/>                    stack.pop();<br\/>            }<br\/>            else \/\/ an operator is encountered<br\/>            {<br\/>                while (!stack.isEmpty() &amp;&amp; Prec(c) &lt;= Prec(stack.peek()))<br\/>                    result += stack.pop();<br\/>                stack.push(c);<br\/>            }<br\/>      <br\/>        }<br\/>      <br\/>        \/\/ pop all the operators from the stack<br\/>        while (!stack.isEmpty())<br\/>            result += stack.pop();<br\/>      <br\/>        return result;<br\/>    }<br\/>   <br\/>    \/\/ Driver method <br\/>    public static void main(String[] args) <br\/>    {<br\/>        String exp = &quot;a+b*(c^d-e)^(f+g*h)-i&quot;;<br\/>        System.out.println(infixToPostfix(exp));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>abcd^e-fgh*+^*+i-<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Infix to Postfix Conversion using Stack &#8211; Data Structure &#8211; Infix expression:The expression of the form a op b.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,2139,79607],"tags":[79896,79892,79926,79895,79894,79927,79891,79893,79890],"class_list":["post-26813","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-java","category-stack","tag-algorithm-for-evaluation-of-postfix-expression","tag-algorithm-for-infix-to-postfix-conversion-using-stack-in-c","tag-algorithm-to-convert-infix-to-postfix-expression-in-data-structure","tag-infix-to-postfix-algorithm-geeksforgeeks","tag-infix-to-postfix-algorithm-java","tag-infix-to-postfix-algorithm-with-parentheses","tag-infix-to-postfix-conversion-using-stack-in-c","tag-infix-to-postfix-using-stack-c-code","tag-infix-to-prefix-algorithm"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26813","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26813"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26813\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26813"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26813"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26813"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}