C实现
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef struct stack
{
char *base;
char *top;
} stack;
int pre(char sign)
{
switch (sign)
{
case '+':
case '-':
return 1;
break;
case '*':
case '/':
return 2;
break;
case '^':
return 3;
break;
default:
return 0;
break;
}
}
int main()
{
stack sign;
int n, i;
char expre[100];
scanf("%d", & n);
while (n--)
{
sign.base = (char *)malloc(100 * sizeof(char));
sign.top = sign.base + 1;
*sign.base = '#';
scanf("%s", expre);
for (i = 0; expre[i] != '#'; i++)
{
if (expre[i] == '(')
{
*sign.top++ = expre[i];
}
else if (expre[i] == ')')
{
while (*(sign.top - 1) != '(')
{
printf("%c", * (sign.top - 1));
sign.top--;
}
sign.top--;
}
else if (expre[i] == '+' || expre[i] == '-' || expre[i] == '*' || expre[i] == '/' || expre[i] == '^')
{
while (((*(sign.top - 1) == expre[i]) && (expre[i] == '^')) ? (pre(*(sign.top - 1)) > pre(expre[i])) : (pre(*(sign.top - 1)) >= pre(expre[i])))
{
printf("%c", * (sign.top - 1));
sign.top--;
}
*sign.top++ = expre[i];
}
else printf("%c", expre[i]);
}
while (sign.top != sign.base + 1)
{
printf("%c", * (sign.top - 1));
sign.top--;
}
printf("\n");
}
return 0;
}