Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class InfixToPostfixProgram {
- public static void main(String[] args) {
- Stack<String> stack = new Stack<String>();
- Scanner input = new Scanner(System.in);
- String exp = input.next();
- LinkedList <String>list= new LinkedList<String>();
- boolean prevPriority = false;
- boolean hasPriority = false;
- for (int i=0; i<exp.length(); i++) {
- String s = exp.charAt(i)+"";
- if(s.equals("+") || s.equals("-")) {
- while(!stack.isEmpty())
- {
- String tkn=stack.pop();
- if((tkn.equals("*") || tkn.equals("/") || tkn.equals("^")) && hasPriority == false )
- list.add(tkn);
- else if(prevPriority) {
- list.add(tkn);
- prevPriority = false;
- }
- else{
- stack.push(tkn);
- break;
- }
- }
- hasPriority = false;
- stack.push(s);
- }
- else if ((s.equals("*") || s.equals("/")))
- {
- while(!stack.isEmpty())
- {
- String tkn=stack.pop();
- if(tkn.equals("^") && hasPriority == false)
- list.add(tkn);
- else if(prevPriority) {
- list.add(tkn);
- prevPriority= false;
- }
- else{
- stack.push(tkn);
- break;
- }
- }
- hasPriority = false;
- stack.push(s);
- }
- else if (s.equals("^"))
- {
- while(!stack.isEmpty())
- {
- String tkn=stack.pop();
- if(prevPriority) {
- list.add(tkn);
- prevPriority = false;
- }else{
- stack.push(tkn);
- break;
- }
- }
- hasPriority = false;
- stack.push(s);
- }
- else if (s.equals(")"))
- {
- prevPriority = true;
- }
- else if (s.equals("(")) {
- hasPriority = true;
- }
- else {
- list.add(s);
- }
- }
- while(!stack.isEmpty())
- {
- list.add(stack.pop());
- }
- System.out.println(list);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement