参照严蔚敏<<数据结构>>第2版算法3.22
当输入 ‘#’ 时代表表示式结束
算法实现:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//定义栈的数据结构
typedef int ElemType;
typedef struct StackNode {
ElemType data;
struct StackNode* next;
}StackNode, *LinkStack;
//算符间的优先级表
char CList[7][7] =
{
{'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=',' ' },
{ '>','>','>','>',' ','>','>' },
{ '<','<','<','<','<',' ','=' },
};
//定义七种算符
char *Op = "+-*/()#";
//初始化栈
void InitStack(LinkStack &L)
{
L = NULL;
}
//元素入栈
void Push(LinkStack &L, ElemType e)
{
StackNode* p = (StackNode*)malloc(sizeof(StackNode));
p->data = e;
p->next = L;
L = p;
}
//弹出栈顶元素值
void Pop(LinkStack &L, ElemType &e)
{
if (L == NULL) return;
e = L->data;
StackNode *p = L;
L = L->next;
delete p;
}
//获取栈顶元素值
ElemType GetTop(LinkStack L)
{
if (L)
return L->data;
}
//实现操作数的运算
int Operate(int a, char theta, int b)
{
switch (theta)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
}
//字符串转数字
int Atoi(char *str)
{
int res = 0;
while (*str)
res = res * 10 + (*str++ - '0');
return res;
}
//判断字符是否为运算符
bool In(char c)
{
int i = 0;
while (Op[i]&&Op[i] != c)
i++;
return i < 7;
}
//运算符优先级比较函数
char Precede(char c1, char c2)
{
char* p = Op;
int i = 0;
while (*p++!=c1)
i++;
int j = 0;
p = Op;
while (*p++ != c2)
j++;
return CList[i][j];
}
//表达式求值函数
int EvaluateExpression()
{
LinkStack OPND, OPTR;
InitStack(OPND);
InitStack(OPTR);
Push(OPTR, '#');
char ch;
cin >> ch;
while (ch != '#' || GetTop(OPTR) != '#')
{
if (!In(ch))
{
int i = 0;
char data[20] = {'\0'};
data[i++] = ch;
cin >> ch;
while (!In(ch))
{
data[i++] = ch;
cin >> ch;
}
Push(OPND, Atoi(data));
}
else
{
switch (Precede(GetTop(OPTR), ch))
{
case '<':
Push(OPTR, ch);
cin >> ch;
break;
case '>':
int theta;
Pop(OPTR, theta);
int a, b;
Pop(OPND, b); Pop(OPND, a);
Push(OPND, Operate(a, theta, b));
break;
case '=':
Pop(OPTR, theta);
cin >> ch;
break;
}
}
}
return GetTop(OPND);
}
//主函数
int main()
{
cout<<EvaluateExpression()<<endl;
return 0;
}
输入: 3*(7-2)#
输出:15
输入: 4*7-21#
输出:7
输出:3*(4-2)*6/9#
输出:4