严格的说,这不能说是解题报告,因为我的代码还没有获得AC,一直是WrongAnswer,但是我找了很多的测试数据,和其他程序的结果是一样的,很郁闷吧。大伙也可以看看我的程序,看看我是不是有什么地方没考虑到。
题目地址 http://acm.nyist.net/JudgeOnline/problem.php?pid=467
我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<memory.h>
char* convert(char *str);
int superior(char c);
char pop(char *str);
void push(char *str,char c);
char take(char *stack);
int main()
{
char str[1000];
int n;
char *destStr;
scanf("%d\n",&n);
for(;n > 0;n --)
{
gets(str);
destStr = convert(str);
printf(destStr);
printf("\n");
free(destStr);
}
return 0;
}
char* convert(char *str)
{
char stack[1000] = {'\0'};
char *destStr = (char *)malloc(1000);
memset(destStr,0,1000);
if(destStr == NULL)
{
printf("Error 1 ...\n");
exit(0);
}
while(*str != '=' && *str != '\0')
{
if(isdigit(*str) || *str == '.')
{
while(isdigit(*str) || *str == '.')
{
push(destStr,*str);
str++;
}
str--;
push(destStr,' ');
}
else if(*str == '(')
{
push(stack,'(');
}
else if(*str == ')')
{
while(take(stack) != '(')
{
push(destStr,pop(stack));
push(destStr,' ');
}
pop(stack);
}
else if(*str == '+' || *str == '-' || *str == '*' || *str == '/')
{
if(strlen(stack) == 0 || superior(*str) > superior(take(stack)))
{
push(stack,*str);
}
else
{
while(take(stack) != '(' && take(stack) != '\0')
{
push(destStr,take(stack));
push(destStr,' ');
pop(stack);
}
push(stack,*str);
}
}
//一个栈最多有两个元素
//而且那一个最后才会弹出。。。
//
else
{
printf("Testing%cTesting\n",*(str));
printf("Error 2 ... \n");
exit(0);
}
str++;
}
while(take(stack) != '\0' && take(stack) != '(')
{
if(strlen(stack) != 0)
{
push(destStr,take(stack));
push(destStr,' ');
pop(stack);
}
else
break;
}
push(destStr,'=');
push(destStr,'\0');
return destStr;
}
int superior(char c)
{
if(c == '+' || c == '-')
{
return 1;
}
else if(c == '*' || c == '/')
{
return 2;
}
else if(c == '(' || c == '\0')
{
return 3;
}
else
{
printf("Error 3 ...\n");
printf("Testing%dTesting\n",c);
return -1;
}
}
void push(char *str,char c)
{
str[strlen(str)] = c;
str[strlen(str)] = '\0';
}
char pop(char *str)
{
char c;
c = str[strlen(str) - 1];
str[strlen(str) - 1] = '\0';
return c;
}
char take(char *stack)
{
if(strlen(stack) == 0)
return '\0';
else
return stack[strlen(stack) - 1];
}
这个OJ是老师推荐的,我觉得不错的功能之一是可以看问题的难度。我一直是做难度为3的题目。
争取每天AC一道题!