描述
给定一个字符串描述的算术表达式,计算出结果值。
输入字符串长度不超过100,合法的字符包括”+, -, *, /, (, )”,”0-9”,字符串内容的合法性及表达式语法的合法性由做题者检查。本题目只涉及整型计算。
输入描述:
输入算术表达式
输出描述:
计算出结果值
示例1
输入:
400+5
输出:
405
自己实现了两个栈
负号补0算法
波兰式算法
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define INIT_STACK_SIZE 64
typedef struct
{
int *base;
int *top;
int size;
} stack_num;
typedef struct
{
char *base;
char *top;
int size;
} stack_op;
void push_num(stack_num *num, int val)
{
if(num->top-num->base >= num->size)
{
num->base = (int* )realloc(num->base, (num->size+8)*sizeof(int));
num->top = num->size+num->base;
num->size = num->size+8;
}
*(num->top) = val;
(num->top)++;
}
int pop_num(stack_num *num)
{
int ret;
if(num->top > num->base)
{
ret = (*(num->top-1));
(num->top)--;
return ret;
}
else
{
return 0;
}
}
void push_op(stack_op *op, char ch_op)
{
if(op->top-op->base >= op->size)
{
op->base = (char* )realloc(op->base, (op->size+8)*sizeof(char));
op->top = op->size+op->base;
op->size = op->size+8;
}
*(op->top) = ch_op;
(op->top)++;
}
char pop_op(stack_op *op)
{
char ret;
if(op->top > op->base)
{
ret= (*(op->top-1));
(op->top)--;
return ret;
}
else
{
return 0;
}
}
int is_digit(char a)
{
if(a>='0' && a<='9')
{
return 1;
}
else
{
return 0;
}
}
int calcu(int a, int b, char op)
{
switch (op)
{
case '+':
return (a+b);
break;
case '-':
return (a-b);
break;
case '*':
return (a*b);
break;
case '/':
return (a/b);
break;
}
return 0;
}
int cmp(char a, char b)
{
if(a=='+' || a=='-')
{
if(b=='+' || b=='-' || b==')' || b=='#')
{
return 1;
}
else if(b=='*' || b=='/' || b=='(')
{
return -1;
}
}
else if(a=='*' || a=='/')
{
if(b=='+' || b=='-' || b==')' || b=='#' || b=='*' || b=='/')
{
return 1;
}
else if(b == '(')
{
return -1;
}
}
else if(a == '(')
{
if(b == ')')
{
return 0;
}
return -1;
}
else if(a == ')')
{
return 1;
}
return 0;
}
int main(void)
{
int val;
int i, j, k;
char str[100] = {0};
stack_num num;
stack_op op;
num.base = (int *)calloc(INIT_STACK_SIZE, sizeof(int));
num.top = num.base;
num.size = INIT_STACK_SIZE;
op.base = (char *)calloc(INIT_STACK_SIZE, sizeof(char));
op.top = op.base;
op.size = INIT_STACK_SIZE;
scanf("%s", str);
for(i=0; i<strlen(str); i++)
{
if(str[i]=='-')
{
// 只有在'-'前面是'('时才需要补0
if(i==0 || str[i-1]=='(')
{
for(j=strlen(str)-1; j>=i; j--)
{
str[j+1] = str[j];
}
str[i] = '0';
}
}
}
i = strlen(str);
str[i] = '#';
i = 0;
while(i < strlen(str))
{
if(is_digit(str[i]) == 1)
{
val = 0;
while(i<strlen(str) && is_digit(str[i])==1)
{
val = val*10;
val = val+str[i]-'0';
i++;
}
push_num(&num, val);
}
if(i >= strlen(str))
{
break;
}
if(is_digit(str[i]) == 0)
{
if(op.base == op.top)
{
push_op(&op, str[i]);
i++;
}
else
{
if(cmp(*(op.top-1), str[i]) > 0)
{
int val1 = pop_num(&num);
int val2 = pop_num(&num);
push_num(&num, calcu(val2, val1, pop_op(&op)));
}
else if(cmp(*(op.top-1), str[i]) < 0)
{
push_op(&op, str[i]);
i++;
}
else
{
pop_op(&op);
i++;
}
}
}
}
printf("%d\n", *(num.base));
free(num.base);
free(op.base);
return 0;
}