实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
示例:
输入: “1 + 1”
输出: 2
解法详谈:
是这里使用的是双栈(操作数栈、操作符栈),对操作数和操作符进行压栈
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STACK_SIZE 1000
typedef int ElemType;
typedef int Status;
#define OK 1
#define ERROR -1
typedef struct SqStack
{
int top;
int bottom;
ElemType array[STACK_SIZE];
}SqStack;
Status Init_Stack(SqStack *S)
{
S->top = S->bottom =0;
return OK;
}
Status Push(SqStack *S, ElemType e)//e为待压入的元素
{
int a = 0;
if(S->top - S->bottom == STACK_SIZE - 1)
{
printf("This stack is full!Push\n\n");
a = ERROR;
}
else
{
S->array[S->top] = e;
S->top++;
a = OK;
}
return a;
}
Status Pop(SqStack *S){
int e;
if(S->bottom == S->top)
printf("This stack is empty!Pop\n\n");
e = S->array[(S->top) - 1];
S->top--;
//printf("%c",e);
return e;
}
Status ISNull(SqStack *S)
{
if(S->bottom == S->top)
{
return OK;
}
else
{
return ERROR;
}
}
Status GetTop(SqStack *S)
{
int e;
if(S->bottom == S->top)
{
printf("The stack is empty!GetTop\n\n");
}
else
{
S->top--;
e = S->array[S->top];
S->top++;
S->array[S->top] = e;
}
return e;
}
Status ClearStack(SqStack *S)
{
S->top = S->bottom;
return OK;
}
int main()
{
SqStack S_oper,S_nums;
Init_Stack(&S_oper);
Init_Stack(&S_nums);
int oper1,oper2;;
char str[] = "(1+(4-5-2)-3)+(6+8)";
char a;
int len = strlen(str);
//printf("%d",len);
for(int i=0;i<len;i++)
{
if(str[i]=='(')
Push(&S_oper,str[i]);
else if(str[i]=='+'||str[i]=='-')
{
if(GetTop(&S_oper)=='-'){
//printf("----");
oper1 = Pop(&S_nums);
oper2 = Pop(&S_nums);
//printf("--%d--",oper2-oper1);
Push(&S_nums,oper2-oper1);
Pop(&S_oper);
}
Push(&S_oper,str[i]);
}
else if(str[i]>='0'&&str[i]<='9')
{
if(i>0&&str[i-1]>='0'&&str[i-1]<='9')
{
int tmp = Pop(&S_nums);
Push(&S_nums,str[i]-'0'+tmp*10);
}
else
Push(&S_nums,str[i]-'0');
}
else if(str[i]==')')
{
a = Pop(&S_oper);
while(a!='(')
{
if(a=='+'){
oper1 = Pop(&S_nums);
oper2 = Pop(&S_nums);
Push(&S_nums,(oper2+oper1));
//printf("++%d++",Pop(&S_nums) + Pop(&S_nums));
}
else if(a=='-')
{
oper1 = Pop(&S_nums);
oper2 = Pop(&S_nums);
//printf("--%d--",oper2-oper1);
Push(&S_nums,oper2-oper1);
}
a = Pop(&S_oper);
}
}
}
while(ISNull(&S_oper)!=1){
a = Pop(&S_oper);
if(a=='+'){
oper1 = Pop(&S_nums);
oper2 = Pop(&S_nums);
Push(&S_nums,(oper2+oper1));
//printf("++%d++",Pop(&S_nums) + Pop(&S_nums));
}
else if(a=='-')
{
oper1 = Pop(&S_nums);
oper2 = Pop(&S_nums);
//printf("--%d--",oper2-oper1);
Push(&S_nums,oper2-oper1);
}
}
printf("%d",Pop(&S_nums));
ClearStack(&S_oper);
ClearStack(&S_nums);
return 0;
}