题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
思路
哈哈哈,这是做了个计算器啊
代码是copy牛友的,,,
学下栈知识再来刷
Answer
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* ToNPL(char* s)
{
char* NPL=(char*)malloc(sizeof(char)*(201));
char* stack=(char*)malloc(sizeof(char)*strlen(s));
int top=-1;
int size=0;
for(int i=0;i<strlen(s);i++)
{
if(s[i]>='0' && s[i]<='9')
{
NPL[size++]=s[i];
}
else
{
if(size>0)
{
if(NPL[size-1]!=' ')
{
NPL[size++]=' ';
}
}
if(top==-1)
{
stack[++top]=s[i];
}
else if(s[i]=='(')
{
stack[++top]=s[i];
}
else if((s[i]=='*' || s[i]=='/')&&(stack[top]=='+' || stack[top]=='-'))
{
stack[++top]=s[i];
}
else if(stack[top]=='(')
{
stack[++top]=s[i];
}
else if(s[i]==')')
{
while(stack[top]!='(')
{
NPL[size++]=stack[top--];
NPL[size++]=' ';
}
top--;
}
else if(s[i]=='+' || s[i]=='-')
{
while(top!=-1)
{
if(stack[top]=='(')
{
break;
}
NPL[size++]=stack[top--];
NPL[size++]=' ';
}
stack[++top]=s[i];
}
else if(s[i]=='*' || s[i]=='/')
{
while(top!=-1)
{
if(stack[top]=='+' || stack[top]=='-' || stack[top]=='(')
{
break;
}
NPL[size++]=stack[top--];
NPL[size]==' ';
}
stack[++top]=s[i];
}
}
}
if(NPL[size-1]!=' ')
{
NPL[size++]=' ';
}
while(top!=-1)
{
NPL[size++]=stack[top--];
NPL[size++]=' ';
}
NPL[size-1]='\0';
free(stack);
return NPL;
}
int caculate(char* s)
{
int* stack=(int*)malloc(sizeof(int)*100);
int top=-1;
for(int i=0;i<strlen(s);i++)
{
if(s[i]>='0' && s[i]<='9')
{
int j=i;
char* temp=(char*)malloc(sizeof(char)*100);
while(s[j]!=' ')
{
temp[j-i]=s[j];
j++;
}
temp[j-i]='\0';
i=j;
int num=atoi(temp);
free(temp);
stack[++top]=num;
}
else if(s[i]=='+')
{
int temp1=stack[top--];
int temp2=stack[top--];
int temp3=temp2+temp1;
stack[++top]=temp3;
}
else if(s[i]=='-')
{
int temp1=stack[top--];
int temp2=stack[top--];
int temp3=temp2-temp1;
stack[++top]=temp3;
}
else if(s[i]=='*')
{
int temp1=stack[top--];
int temp2=stack[top--];
int temp3=temp2*temp1;
stack[++top]=temp3;
}
else if(s[i]=='/')
{
int temp1=stack[top--];
int temp2=stack[top--];
int temp3=temp2/temp1;
stack[++top]=temp3;
}
}
int ans=stack[top--];
free(stack);
return ans;
}
int main()
{
char* str=(char*)malloc(sizeof(char)*101);
scanf("%s\n",str);
char* str_process=(char*)malloc(sizeof(char)*201);
int size=0;
for(int i=0;i<strlen(str);i++)
{
if(str[i]=='-')
{
if(i==0)
{
str_process[size++]='0';
str_process[size++]=str[i];
}
else if(str[i-1]==')')
{
str_process[size++]=str[i];
}
else if(str[i-1]<'0' || str[i-1]>'9')
{
str_process[size++]='0';
str_process[size++]=str[i];
}
else
{
str_process[size++]=str[i];
}
}
else
{
str_process[size++]=str[i];
}
}//给负数补0
str_process[size]='\0';
char* str_NPL=ToNPL(str_process);//将中缀表达式改为后缀表达式
int str_ans=caculate(str_NPL);//计算后缀表达式
printf("%d\n",str_ans);
free(str_NPL);
free(str_process);
return 0;
}