4. Transform the Expression Problem code: ONP
#include<stdio.h>
#include<ctype.h>
char stack[1000];
int top;
void initialize_stack()
{
top=-1;
}
char pop()
{
return stack[top--];
}
void push(char x)
{
stack[++top]=x;
}
int precedence(char op)
{
if (op=='^')
return 3;
if((op=='*')||(op=='/'))
return 2;
else if ((op=='+')||(op=='-'))
return 1;
}
int greater_or_equal( char op1 , char op2 )
{
return(precedence(op1)>=precedence(op2));
}
int is_operator(char c)
{
return (c=='*')||(c=='/')||(c=='+')||(c=='-' ||c=='^');
}
int main()
{
int in;
char c;
in=0;
initialize_stack();
int t;
scanf("%d\n",&t);
while (t--)
{
while((c=getchar())!='\n')
{
if ( (isalpha(c)) ||(c=='.'))
{
printf("%c",c);
}
else if(is_operator(c))
{
while( (top!=-1) && (stack[top]!='(') && (greater_or_equal(stack[top],c)) )
printf("%c",pop());
push(c);
}
else if(c=='(')
push(c);
else if(c==')')
{
while(stack[top]!='(')
printf("%c",pop());
top--;
}
}
while(top!=-1)
printf("%c",pop());
printf("\n");
}
}
#include<stdio.h>
#include<ctype.h>
char stack[1000];
int top;
void initialize_stack()
{
top=-1;
}
char pop()
{
return stack[top--];
}
void push(char x)
{
stack[++top]=x;
}
int precedence(char op)
{
if (op=='^')
return 3;
if((op=='*')||(op=='/'))
return 2;
else if ((op=='+')||(op=='-'))
return 1;
}
int greater_or_equal( char op1 , char op2 )
{
return(precedence(op1)>=precedence(op2));
}
int is_operator(char c)
{
return (c=='*')||(c=='/')||(c=='+')||(c=='-' ||c=='^');
}
int main()
{
int in;
char c;
in=0;
initialize_stack();
int t;
scanf("%d\n",&t);
while (t--)
{
while((c=getchar())!='\n')
{
if ( (isalpha(c)) ||(c=='.'))
{
printf("%c",c);
}
else if(is_operator(c))
{
while( (top!=-1) && (stack[top]!='(') && (greater_or_equal(stack[top],c)) )
printf("%c",pop());
push(c);
}
else if(c=='(')
push(c);
else if(c==')')
{
while(stack[top]!='(')
printf("%c",pop());
top--;
}
}
while(top!=-1)
printf("%c",pop());
printf("\n");
}
}
No comments:
Post a Comment