/**
* Tugas : ETS_Soal 2_Infix - Postfix
*
* Rafael Asi Kristanto Tambunan
* 5025201168
* Teknik Informatika
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Stack <type>{
private List<type> list;
private int currentIndex;
public Stack() // constructor
{
list = new ArrayList<type>();
currentIndex = -1;
}
public void push(type data) // put item on top of stack
{
list.add(data);
currentIndex++;
}
public type pop() // take item from top of stack
{
type removed=list.remove(currentIndex);
currentIndex--;
return removed;
}
public type peek() // peek at top of stack
{
return list.get(currentIndex);
}
public boolean isEmpty() // return size
{
if(list.size()==0) return true;
else return false;
}
public void clear() // remove all elements in the Stack
{
list.clear();
currentIndex = -1;
}
}
class Transformation{
private static int type(char kar)
{
switch (kar)
{
case \'+\': case \'-\':
return 1;
case \'*\': case \'/\': case \'%\':
return 2;
case \'^\':
return 3;
default:
return -1;
}
}
public static void Post(String expression){
Stack <Character> theStack = new Stack(); //to save the operator
String Post = ""; //to save the Postfix form
for(int i = 0; i < expression.length(); i++){
char ch = expression.charAt(i);
if(Character.isLetterOrDigit(ch))
{
Post += ch;
}
else if(ch == \'(\')
{
theStack.push(ch);
}
else if(ch == \')\')
{
while(!theStack.isEmpty() && !theStack.peek().equals(\'(\'))
{
Post+=theStack.pop();
}
theStack.pop();
}
else{
while(!theStack.isEmpty()&&type(theStack.peek()) >= type(ch))
{
Post+=theStack.pop();
}
theStack.push(ch);
}
}
while(!theStack.isEmpty())
{
Post+=theStack.pop();
}
System.out.println(Post);
System.out.println();
}
}
public class Infix_Postfix {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String infix;
System.out.print("Enter the Arithmetics : ");
infix = input.nextLine();
System.out.print("\\n===================================\\n\\n");
System.out.println("Infix Expression : " + infix);
System.out.print("Postfix Expression : ");
Transformation.Post(infix);
}
}