Tuesday, May 6, 2014
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important application of stack. Most of the codes that you will find dont take into considerations the exponent and parenthesis. Here in our example we will consider everything and it will be able to convert any infix expression to postfix containing exponent(^) and parenthesis("(",")"). In our example we have also shown the current symbol processed, stack status and current postfix expression. We have solved it in the following way
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
- First push a sentinel element # to denote end of stack
- Scan each symbol of input infix expression
- If symbol is operator then check precedence with operator on stack top and take necessary action
- If left parenthesis then push it, and if right parenthesis then pop continously from stack till a left parenthesis is found
- If all symbols are scanned then pop all elements from stack and ad to postfix till # found.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner; import java.util.Stack; public class InfixToPostfix { /** * Checks if the input is operator or not * @param c input to be checked * @return true if operator */ private boolean isOperator(char c){ if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^') return true; return false; } /** * Checks if c2 has same or higher precedence than c1 * @param c1 first operator * @param c2 second operator * @return true if c2 has same or higher precedence */ private boolean checkPrecedence(char c1, char c2){ if((c2 == '+' || c2 == '-') && (c1 == '+' || c1 == '-')) return true; else if((c2 == '*' || c2 == '/') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/')) return true; else if((c2 == '^') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/')) return true; else return false; } /** * Converts infix expression to postfix * @param infix infix expression to be converted * @return postfix expression */ public String convert(String infix){ System.out.printf("%-8s%-10s%-15s\n", "Input","Stack","Postfix"); String postfix = ""; //equivalent postfix is empty initially Stack<Character> s = new Stack<>(); //stack to hold symbols s.push('#'); //symbol to denote end of stack System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix); for(int i = 0; i < infix.length(); i++){ char inputSymbol = infix.charAt(i); //symbol to be processed if(isOperator(inputSymbol)){ //if a operator //repeatedly pops if stack top has same or higher precedence while(checkPrecedence(inputSymbol, s.peek())) postfix += s.pop(); s.push(inputSymbol); } else if(inputSymbol == '(') s.push(inputSymbol); //push if left parenthesis else if(inputSymbol == ')'){ //repeatedly pops if right parenthesis until left parenthesis is found while(s.peek() != '(') postfix += s.pop(); s.pop(); } else postfix += inputSymbol; System.out.printf("%-8s%-10s%-15s\n", ""+inputSymbol,format(s.toString()),postfix); } //pops all elements of stack left while(s.peek() != '#'){ postfix += s.pop(); System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix); } return postfix; } /** * Formats the input stack string * @param s It is a stack converted to string * @return formatted input */ private String format(String s){ s = s.replaceAll(",",""); //removes all , in stack string s = s.replaceAll(" ",""); //removes all spaces in stack string s = s.substring(1, s.length()-1); //removes [] from stack string return s; } public static void main(String[] args) { InfixToPostfix obj = new InfixToPostfix(); Scanner sc = new Scanner(System.in); System.out.print("Infix : \t"); String infix = sc.next(); System.out.print("Postfix : \t"+obj.convert(infix)); } }-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------Infix : A+(B*C-(D/E^F)*G)*H Input Stack Postfix # A # A + #+ A ( #+( A B #+( AB * #+(* AB C #+(* ABC - #+(- ABC* ( #+(-( ABC* D #+(-( ABC*D / #+(-(/ ABC*D E #+(-(/ ABC*DE ^ #+(-(/^ ABC*DE F #+(-(/^ ABC*DEF ) #+(- ABC*DEF^/ * #+(-* ABC*DEF^/ G #+(-* ABC*DEF^/G ) #+ ABC*DEF^/G*- * #+* ABC*DEF^/G*- H #+* ABC*DEF^/G*-H #+ ABC*DEF^/G*-H* # ABC*DEF^/G*-H*+ Postfix : ABC*DEF^/G*-H*+-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Labels:Algorithms
Subscribe to:
Post Comments
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...
excellent program
ReplyDeleteIt doesn't recognize modulo sign as an operator
ReplyDeletethis program saved my grade,, thanks... it is possible to make this program recognise
ReplyDeletethe modulo sign...
Hello, this program do not trace any invalid input. For example ")A+B+C" is an invalid infix input but the program do not tell the user. Hope this program will improve!
ReplyDeleteHello, this program is just so good but my problem is that the program cannot recognize the modulo(%) as an operator. Can you help me?
ReplyDeleteBut i need by using our own stack class
ReplyDelete