infix to postfix
class infix_to_postfix { public static void main(String[] args) { String input="1+2*4/5-7+3/6"; infix_to_postfix object=new infix_to_postfix(); intopost(input); } static String input="1+2*4/5-7+3/6"; static int l=input.length(); static char array[]=new char[l]; static int top=-1; static int precedence(char ch) { if(ch=='+' || ch=='-') { return 1; } if(ch=='/' || ch=='*') { return 2; } if(ch=='^') { return 3; } return -1; } public static void push(char ch) { top++; array[top]=ch; } public static void pop() { System.out.print(array[top]); top--; } public static char peek() { return array[top]; } public static boolean isempty() { if(top==-1) { return true; } return false; } static void intopost(String input) { for (int j = 0; j < input.length(); j++) { char ch = input.charAt(j); if((ch>='a'&&ch<='z')||(ch>='0' &&ch<='9') || (ch>='A' && ch<='Z') ) { System.out.print(ch); } else if(ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='^' ) { if(top==-1) { push(ch); } else { while(precedence(ch)<=precedence(array[top]) ) { pop(); if(top==-1) { break; } } push(ch); } } else if(ch=='(') { push(ch); } else if(ch==')') { while(!(peek()=='(' ) ) { pop(); } } } while(!isempty()) { pop(); } } }
infix to postfix
Reviewed by Unknown
on
02:36
Rating:
No comments: