SPOJ
Problem Code : ONP
#include<stdio.h>
int getPre(char x)
{
switch(x)
{
case '^': return 4;
case '*':
case '/': return 3;
case '+':
case '-': return 2;
case '(': return 1;
}
return 0;
}
int main()
{
char Infix[400], Postfix[400], Stack[400];
int in_ptr, po_ptr, st_ptr, t,i;
scanf("%d",&t);
while(t--)
{
po_ptr=st_ptr=-1;
scanf("%s",Infix);
for(i=0; Infix[i]!='\0'; i++)
{
if(Infix[i] == '(')
{
st_ptr++;
Stack[st_ptr]='(';
}
else if(Infix[i] == ')')
{
while(Stack[st_ptr]!='(')
{
po_ptr++;
Postfix[po_ptr] = Stack[st_ptr];
st_ptr--;
}
st_ptr--;
}
else if(Infix[i] == '+' || Infix[i] == '-' || Infix[i] == '*' || Infix[i] == '/' || Infix[i] == '^')
{
while(getPre(Stack[st_ptr]) >= getPre(Infix[i]))
{
po_ptr++;
Postfix[po_ptr] = Stack[st_ptr];
st_ptr--;
}
st_ptr++;
Stack[st_ptr] = Infix[i];
}
else
{
po_ptr++;
Postfix[po_ptr] = Infix[i];
}
}
Postfix[po_ptr+1] = '\0';
printf("%s\n",Postfix);
}
return 0;
}
No comments:
Post a Comment