1. Code does not check for malformed expressions.
2. Operators recognised are +,-,*,/.
3. Unary positive and negative operators are not supported.

Java:

public class InfixToPostfix {
  
  public String convert(String input) {
	char[] chars = input.toCharArray();
	
	StringBuffer postfixExpression = new StringBuffer(input.length());
	
	LinkedList<Character> stack = new LinkedList<Character>();
	
	for (char chr : chars) {
	  if (isLetter(chr)) {
		postfixExpression.append(chr);
	  } else if (chr == '(') {
		stack.add(chr);
	  } else if (chr == ')') {
		while (! stack.isEmpty()) {
		  char chr1 = stack.removeLast();
		  if (chr1 != '(') {
			postfixExpression.append(chr1);
		  }
		}
	  } else {
		if (stack.isEmpty()) {
		  stack.add(chr);
		} else {
		  while (! stack.isEmpty()) {
			if (stack.getLast() == '(') {
			  break;
			}
			
			if ((stack.getLast() == '+' || stack.getLast() == '-') && (chr == '*' || chr == '/')) {
			  break;
			} else {
			  postfixExpression.append(stack.removeLast());
			}
		  }
		  stack.add(chr);
		}
	  }
	}
	
	while (! stack.isEmpty()) {
	  postfixExpression.append(stack.removeLast());
	}
	
	return postfixExpression.toString();
  }
  
  public static boolean isLetter(char chr) {
	try {
	  Integer.parseInt(String.valueOf(chr));
	  return true;
	} catch (NumberFormatException nfe) {
	  return false;
	}
  }

  public static void main(String[] args) {
	InfixToPostfix postFixToInfix = new InfixToPostfix();
	System.out.println(postFixToInfix.convert("1*(2+3)-4/(5+6)"));
  }
  
}

Python:

infix_expression = "3+4*3"

postfix_expression = ""
stack = [];

for char in infix_expression :
	try :
		char = int(char);
		postfix_expression = postfix_expression + str(char)
	except :
		if char == "(" :
			stack.append(char);
		elif char == ")" :
			while len(stack) != 0 :
				char1 = stack.pop()
				if char1 != "(" :
					postfix_expression = postfix_expression + char1
		else :
			if len(stack) == 0 :
				stack.append(char)
			else :
				while len(stack) != 0 :
					if stack[len(stack) - 1] == "(" :
						break

					if (stack[len(stack) - 1] == "+" or stack[len(stack) - 1] == "-") and (char == "*" or char == "/") :
						break
					else :
						postfix_expression = postfix_expression + str(stack.pop())

				stack.append(char)


while len(stack) != 0 :
	postfix_expression = postfix_expression + str(stack.pop())

print postfix_expression
Advertisements