堆栈之表达式求值
@[.DataStructure]
1. 后缀表达式求值
#include<iostream>
#include<cstdio>
#include<string.h>
#include<math.h>
using namespace std;
#define ElementType double
#define MAXSIZE 100
#define MAXOP 100
#define INFINITY 1e9 //代表正无穷
typedef enum {num, opr, end1} Type;
typedef struct SNode * PtrtoSNode;
struct SNode
{
ElementType Data;
PtrtoSNode Next;
};
typedef PtrtoSNode Stack;
bool IsEmpty(Stack S)
{
return(S->Next == NULL);
}
Stack CreatStack()
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Next = NULL;
return S;
}
bool Push(Stack S, ElementType X)
{
PtrtoSNode TmpCell;
TmpCell = (PtrtoSNode)malloc(sizeof(struct SNode));
TmpCell->Data = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
return true;
}
#define Error -100
ElementType Pop(Stack S)
{
//删除并返回栈顶元素
PtrtoSNode FirstCell;
ElementType TopElem;
if (IsEmpty(S))
{
cout << "the stack is empty" << endl;
return Error;
}
else
{
FirstCell = S->Next;
TopElem = FirstCell->Data;
S->Next = FirstCell->Next;
free(FirstCell);
return TopElem;
}
}
Type GetOp(char * Expr, int * start,char * str)
{
//从*start开始读入下一个 对象(操作数或运算符),并保存在字符串str中
int i = 0;
//跳过表达式前的空格
while ((str[0] = Expr[(*start)++]) == ' ');
while (str[i] != ' '&& str[i] != '\0')
str[++i] = Expr[(*start)++];
if (str[i]=='\0')
{
(*start)--;
}
str[i] = '\0';
if (i == 0)
{
return end1;
}
else if (isdigit(str[0]) || isdigit(str[1]))
return num;
else
return opr;
}
ElementType PostfixExp(char * Expr)
{
Stack S;
Type T;
ElementType Op1, Op2;
char str[MAXOP];
int start = 0;
// 申请一个新堆栈
S = CreatStack();
Op1 = Op2 = 0;
while ((T=GetOp(Expr, &start, str))!= end1)
{
if (T == num)
Push(S, atof(str));
else
{
if (!IsEmpty(S)) Op2 = Pop(S);
else
{
Op2 = INFINITY;
}
if (!IsEmpty(S)) Op1 = Pop(S);
else
{
Op2 = INFINITY;
}
switch (str[0])
{
case '+': Push(S, Op1 + Op2); break;
case '-': Push(S, Op1 - Op2); break;
case '*': Push(S, Op1 * Op2); break;
case '/':
{
if (Op2 != 0.0)
{
Push(S, Op1 / Op2);
}
else
{
cout << "Error have a non-zero term in the denominator" << endl;
Op2 = INFINITY;
}
}
break;
default:
cout << "Unknown operator" << endl;
Op2 = INFINITY;
break;
}
if (Op2 >= INFINITY) break;
}
}
if (Op2 < INFINITY)
{
if (!IsEmpty(S))
Op2 = Pop(S);
else
Op2 = INFINITY;
}
free(S);
return Op2;
}
int main()
{
char Expr[MAXOP];
ElementType f;
gets_s(Expr);
f = PostfixExp(Expr);
if (f < INFINITY)
{
cout << f << endl;
}
else
{
cout << "the exression is illegal" << endl;
}
return 0;
}
2. 中缀表达式求值
数据结构动图资源
https://www.cs.usfca.edu/~galles/visualization/Algorithms.html