#include <iostream>
using namespace std;
#include <stdlib.h>
#include <stdio.h>
#define ERROR 0
#define OK 1
#define OVERFLOW -2
#define STACK_SIZE 100//初始化分配存儲空間
#define STACKINCREMENT 5//存儲空間增量
typedef int SElemType;
typedef struct SqStack{
int *base;
int *top;
int stacksize;
}SqStack;
int InitStack (SqStack *S)//char
{
S->base = (SElemType *)malloc(STACK_SIZE*sizeof(SElemType));
if(!S->base) exit(OVERFLOW);
S->top = S->base;
S->stacksize = STACK_SIZE;
return OK;
}//構造一個空棧
int GetTop(SqStack *S)
{
if(S->top == S->base) return ERROR;
return *(S->top-1);
}//返回棧頂元素
int Push(SqStack *S,SElemType e)//插入e爲棧頂元素
{
if(S->top - S->base >= S->stacksize){
S->base = (SElemType *)realloc(S->base,
(S->stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S->base) exit(OVERFLOW);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*S->top++ = e;
return OK;
}
int Pop(SqStack *S,SElemType *e)
{
if(S->top == S->base) return ERROR;
*e = *--S->top;
return OK;
}
char Precede(char x,char y)//判斷優先級,x爲棧內,y爲棧外
{
if((x=='('&&y==')') || (x=='\n'&&y=='\n'))
return '=';
else if((y=='\n'&&x=='(') || (y==')'&&x=='\n') || (y=='('&&x==')'))
return ERROR;
else if(((y=='+'||y=='-')&&x!='('&&x!='\n') ||
((y=='*'||y=='/')&&x!='-'&&x!='('&&x!='\n'&&x!='+') ||
y==')' || y=='\n')
return '>';
else return '<';
}//判斷優先級函數
int In(char c)
{
if (c=='+' || c=='-' ||
c=='*' || c=='/' ||
c=='(' || c==')' || c=='\n')
return OK;
else return ERROR;
}
int Operate(int a,char theta,int b)//計算基本表達式
{
if (theta=='+')
return a+b;
if (theta=='-')
return a-b;
if (theta=='*')
return a*b;
if (theta=='/')
return a/b;
return ERROR;
}
int EvaluateExpression()
{
SqStack OPTR;//用以寄存運算符
SqStack OPND;//用以寄存操作數
InitStack(&OPTR); Push(&OPTR,'\n');
InitStack(&OPND);
int theta;
int c;
int x;//實際沒用,只是爲了調用pop函數
int y,a,b;
int flag = 0;
c = getchar();
while (c!='\n' || GetTop(&OPTR)!='\n'){
if(!In(c)) {
if (flag == 0){
Push(&OPND,c-48);//輸入整數的時候轉換
c = getchar();//不是運算符則進棧
flag++;
}
else {
Pop(&OPND,&y);
y = y*10+int(c-48);
Push(&OPND,y);
c = getchar();
}
}//if
else{
flag = 0;
switch(Precede(GetTop(&OPTR),c)){
case '<'://棧頂元素優先權低於棧外元素優先權
Push(&OPTR,c);
c = getchar();
break;
case '='://脫括號處理
Pop(&OPTR,&x);//只是爲了除去括號
c = getchar();
break;
case '>'://退棧並且把運算結果入棧
Pop(&OPTR,&theta);
Pop(&OPND,&b);Pop(&OPND,&a);
Push(&OPND,Operate(a,theta,b));
break;
}//switch
}//else
}//while
return GetTop(&OPND);
}
int main()
{
char ch = 'Y';
while(ch != 'N'){
cout<<"Please input the expression:"<<endl;
int answer = EvaluateExpression();
cout<<"The answer is: "<<answer<<endl;
cout<<"Would you want answer espression 'Y' or 'N'"<<endl;
ch = getchar();
getchar();
}
getchar();
return 0;
}
代碼僅供參考,不可以進行浮點數的運算,不支持單目運算,包括整數的+-*/運算。
運行時輸入表達式回車即可