You are on page 1of 4

import java.util.

*;
class StackApplication {

/**
* @param args
*/
public static void main(String[] args) {

Scanner scan = new Scanner(System.in);


CapacityGetterSetter getset = new CapacityGetterSetter();

getset.setCapacity(100);
int inputs = Integer.parseInt(scan.nextLine());

while (inputs >0) {


String pattern = scan.nextLine();
infixpost testinfix = new infixpost();
System.out.println(testinfix.infixtopostfix(pattern));
inputs--;
}
}

class infixpost{
static int Prec(char ch)
{
if(ch=='+'||ch=='-')
return 1;
else if(ch=='*'||ch=='/')
return 2;
else if(ch=='^')
return 3;
return -1;
}
public String infixtopostfix(String input) {
String result="";

stack<Character> S = new StackArray<Character>();


for (int i = 0; i<input.length(); i++)
{
char c = input.charAt(i);
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
S.push(c);
else if (c == ')')
{

while (!S.isEmpty() && S.top() != '(')


result += S.pop();

if (!S.isEmpty() && S.top() != '(')


return "Invalid Expression";
else
S.pop();
}
else if(!S.isEmpty()&&(c=='+'||c=='-'||c=='/'||
c=='*')&&(c==S.top()))
{
return "Invalid Expression";
}
else
{
while (!S.isEmpty() && Prec(c) <= Prec(S.top()))
result += S.pop();
S.push(c);
}

while (!S.isEmpty())
result += S.pop();

return result;
}
}

interface stack<E> {
int size();
boolean isEmpty();
void push(E e);
E pop();
E top();
void printStack();
}

class CapacityGetterSetter {
private static int stackcap;

public int getCapacity() {


return this.stackcap;
}

public void setCapacity(int cap) {


stackcap = cap;
}
}

class StackArray<E> implements stack<E> {


// public static final int CAPACITY=20;
CapacityGetterSetter getset = new CapacityGetterSetter();
private E[] data; // array container
private int t = -1; // index to top position
// constructor
int CAPACITY=0;

public StackArray() {
CAPACITY = getset.getCapacity();
data = (E[]) new Object[CAPACITY];
}

public int size() {


// TODO Auto-generated method stub
return (t + 1);
}

public boolean isEmpty() {


// TODO Auto-generated method stub
return (t < 0);
}

public void push(E e) {


// TODO Auto-generated method stub
if (size() == CAPACITY)
{
System.out.println("StackFullException");
}
else {
t = t + 1;
data[t] = e;
}
}

public E top() {
// TODO Auto-generated method stub
if (isEmpty()){
System.out.println("StackEmptyException");
return null;
}
else {
return data[t];
}
}

public E pop() {
// TODO Auto-generated method stub
if (isEmpty()) {
System.out.println("StackEmptyException");
return null;
} else {
E temp = data[t];
data[t] = null;
t = t - 1;
return temp;
}

public void printStack() {


if (isEmpty())
System.out.println("Empty");
else{
for (int i = 0; i < CAPACITY; i++) {
if(data[i]!=null)
System.out.print(data[i] + " ");
}
System.out.println(" ");
}
}

public void flush(){


for (int i = 0; i < size(); i++) {
pop();
}
}

You might also like