思路:中缀表达式-后缀表达式-求值
参考代码:
#include
#include
#include
#include
#include
#include
#include
// 堆栈的数组实现,数组的大小固定。
template
class stack
{
private:
T *s; // 数组的首地址(栈底)
size_t N; // 指向栈顶第一个空闲块
const size_t size; // 堆栈的大小,固定不变
public:
stack(size_t n) : size(n)
{
s = new T[n]; // 可能抛出异常
N = 0; // 设置栈顶指针
}
~stack()
{
delete [] s;
}
bool empty() const
{
return N == 0;
}
bool full() const
{
return N == size;
}
void push(const T &object)
{
if (full())
{
throw "error: stack is full !";
}
s[N++] = object;
}
T pop()
{
if (empty())
{
throw "error: stack is empty !";
}
return s[--N];
}
T peek() const
{
if (empty())
{
throw "error: stack is empty !";
}
return s[N-1];
}
friend std::ostream& operator<<(std::ostream& os, const stack
{
for (size_t i = 0; i < stk.N; i++)
{
std::cout << stk.s[i] << " ";
}
return os;
}
};
// 堆栈的链表实现
template
class STACK
{
private:
typedef struct node
{
T item;
node *next;
node(T x, node *t = NULL) : item(x), next(t) {}
}*link;
link head; // 指向栈顶第一个有效对象
public:
STACK(size_t n)
{
head = NULL;
}
~STACK() // 也可以用pop的方法删除,但效率低
{
link t = head;
while (t != NULL)
{
link d = t;
t = t->next;
delete d;
}
}
bool empty() const
{
return head == NULL;
}
bool full() const
{
return false;
}
void push(const T &object)
{
head = new node(object, head);
}
T pop()
{
if (empty())
{
throw "error: stack is empty !";
}
T v = head->item;
link t = head->next;
delete head;
head = t;
return v;
}
T peek() const
{
if (empty())
{
throw "error: stack is empty !";
}
return head->item;
}
friend std::ostream& operator<<(std::ostream& os, const STACK
{
for (link t = stk.head; t != NULL; t = t->next)
{
std::cout << t->item << " ";
}
return os;
}
};
// 中缀表达式转化为后缀表达式,仅支持加减乘除运算、操作数为1位十进制非负整数的表达式。
char* infix2postfix(const char *infix, char *postfix)
{
const size_t N = strlen(infix);
if (N == 0 || postfix == NULL)
{
return postfix;
}
stack
for (size_t i = 0; i < N; i++)
{
switch (infix[i])
{
case '(': // 直接忽略左括号
break;
case ')': // 弹出操作符
*postfix++ = opcode.pop();
*postfix++ = ' ';
break;
case '+':
case '-':
case '*':
case '/':
opcode.push(infix[i]); // 压入操作符
break;
default:
if (isdigit(infix[i])) // 如果是数字,直接输出
{
*postfix++ = infix[i];
*postfix++ = ' ';
}
}
}
return postfix;
}
// 后缀表达式转化为中缀表达式,仅支持加减乘除运算、操作数为1位十进制非负整数的表达式。
char* postfix2infix(const char *postfix, char *infix)
{
const size_t N = strlen(postfix);
if (N == 0 || infix == NULL)
{
return infix;
}
*infix = '\0'; // 初始化输出字符串为空串
std::vector
// 初始化,将所有有效字符放入容器
for (size_t i = 0; i < N; i++)
{
if (isdigit(postfix[i]) || postfix[i] == '+'
|| postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/')
{
v.push_back(std::string(1, postfix[i]));
}
}
// 处理每一个操作符
for (std::vector
{
if (*b == "+" || *b == "-" || *b == "*" || *b == "/")
{
copy(v.begin(), v.end(), std::ostream_iterator
std::cout << "------------------------------------------------" << std::endl;
std::string opcode = *(b);
std::string oprand1 = *(b - 2);
std::string oprand2 = *(b - 1);
b = v.erase(b - 2, b + 1); // 删除原来的三个表达式,用一个新的表达式替换
b = v.insert(b, std::string("(") + oprand1 + opcode + oprand2 + std::string(")"));
}
}
for (std::vector
{
strcat(infix, (*b).c_str());
}
return infix;
}
// 计算后缀表达式的值,仅支持加减乘除运算、操作数为非负整数的表达式。
int postfix_eval(const char * postfix)
{
const size_t N = strlen(postfix);
if (N == 0)
{
return 0;
}
STACK
for (size_t i = 0 ; i < N; i++)
{
switch (postfix[i])
{
int op1, op2;
case '+':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 + op2);
break;
case '-':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 - op2);
break;
case '*':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 * op2);
break;
case '/':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 / op2);
break;
default:
if (isdigit(postfix[i])) // 执行类似atoi()的功能
{
operand.push(0);
while (isdigit(postfix[i]))
{
operand.push(10 * operand.pop() + postfix[i++] - '0');
}
i--;
}
}
std::cout << operand << std::endl; // 输出堆栈的内容
}
return operand.pop();
}
// 本程序演示了如何后缀表达式和中缀表达式的相互转换,并利用堆栈计算后缀表达式。
// 转换方向:org_infix --> postfix --> infix
int main(int argc, const char *argv[])
{
// const char *org_infix = "(5*(((9+8)*(4*6))+7))"; // section 4.3
const char *org_infix = "(5*((9*8)+(7*(4+6))))"; // exercise 4.12
std::cout << "原始中缀表达式:" << org_infix << std::endl;
char *const postfix = new char[strlen(org_infix) + 1];
infix2postfix(org_infix, postfix);
std::cout << "后缀表达式:" << postfix << std::endl;
char *const infix = new char[strlen(postfix) + 1];
postfix2infix(postfix, infix);
std::cout << "中缀表达式:" << infix << std::endl;
std::cout << "计算结果是:" << postfix_eval(postfix) << std::endl;
std::cout << "计算结果是:" << postfix_eval("5 9*8 7 4 6+*2 1 3 * + * + *") << std::endl; // exercise 4.13
delete []infix;
delete []postfix;
return 0;
}
我的思路也是先求中缀表达式,之后再求解.
而且能计算多位数 ,小数...
有1个.h文件里面的内容是
//------------------------------------------------------------------
#ifndef STACK //避免重复包含
#define STACK
#define Stack_init_size 100
#define StackIncreament 10
//定义一个栈类型
typedef struct
{
float *base;
float *top;
int stacksize;
}Sqstack;
//定义栈的基本操作
int InitStack(Sqstack &s);
int DestroyStack(Sqstack &s);
int StackEmpty(Sqstack s);
int GetTop(Sqstack s,float &e);
int Push(Sqstack &s,float e);
int Pop(Sqstack &s,float &e);
#endif
//-----------------------------------------------------------------
一个.cpp文件
实现.h文件里面函数的基本操作
//-----------------------------------------------------------------
#include"Stack.h"
#include
int InitStack(Sqstack &s)
{
s.base=(float *)malloc(Stack_init_size*sizeof(float));
if(!s.base) exit(1);
s.top=s.base;
s.stacksize=Stack_init_size;
return 1;
}
int DestroyStack(Sqstack &s)
{
if(!s.base) return 0;
free(s.base);
s.base=s.top=0;
s.stacksize=0;
return 1;
}
int StackEmpty(Sqstack s)
{
if(s.base&&s.top==s.base) return 1;
else return 0;
}
int GetTop(Sqstack s,float &e)
{
if(StackEmpty(s)) return 0;
e=*(s.top-1);
return 1;
}
int Push(Sqstack &s,float e)
{
if(s.top-s.base>=s.stacksize)
{
s.base=(float *)realloc(s.base,(s.stacksize+StackIncreament)*sizeof(float));
if(!s.base) exit(1);
s.top=s.base+s.stacksize;
s.stacksize+=StackIncreament;
}
*s.top++=e;
return 1;
}
int Pop(Sqstack &s,float &e)
{
if(s.top==s.base) return 0;
e=*--s.top;
return 1;
}
//----------------------------------------------------------------
最后一个.cpp文件实现转化成后缀表达式,再求解
//----------------------------------------------------------------
#include"Stack.h"
#include
#include
using namespace std;
////////定义函数实现对两操作符优先级的比较//////////
char precede(char c1,char c2)
{
if((c1=='+'||c1=='-')&&(c2=='+'||c2=='-'||c2==')'||c2=='#'))
return '>';
if((c1=='*'||c1=='/'||c1==')')&&(c2=='+'||c2=='-'||c2=='*'||c2=='/'||c2==')'||c2=='#'))
return '>';
if((c1=='('&&c2==')')||(c1=='#'&&c2=='#'))
return '=';
return '<';
}
//----定义转换函数(由原表达式得到逆波兰式)--------------
//---exp传入原表达式存放位置,suffix为转换后存放的地址-------
void transform(char *suffix, char *exp)
{
Sqstack S;
InitStack(S);Push(S,'#');
char *p=exp; char ch=*p;
int i=0;float c;
while(!StackEmpty(S))
{
if(!(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#'))
suffix[i++]=ch;
else
{
GetTop(S,c);
switch(ch)
{
case '(':
Push(S,ch);break;
case ')':
Pop(S,c);
while(c!='(')
{
suffix[i++]=c;Pop(S,c);
}
break;
default:
while(GetTop(S,c)&&(precede(c,ch)=='>'))
{
suffix[i++]=c;Pop(S,c);
}
if(ch!='#')
{
Push(S,ch);
suffix[i++]=' ';
}
break;
}
}
if(ch=='#')
{
Pop(S,c);
suffix[i++]=ch;
}
else
{
p++;
ch=*p;
}
}
suffix[i]='\0';
DestroyStack(S);
}
float Evaluate(char *exp)
{
Sqstack S;
InitStack(S);
char *p=exp, ch=*p;
float a,b;
char x[10];
int i=0,flag=0;
while(ch!='#')
{
while(!(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#'||ch==' '))
{
x[i++]=ch;
p++;ch=*p;
flag=1;
}
x[i]='\0';
i=0;
// cout<
Push(S,atof(x));
if((ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#'))
{
Pop(S,b);Pop(S,a);
switch(ch)
{
case '+':Push(S,a+b);break;
case '-':Push(S,a-b);break;
case '*':Push(S,a*b);break;
case '/':Push(S,a/b);break;
}
}
p++;ch=*p;flag=0;
}
Pop(S,a);
DestroyStack(S);
return a;
}
//==========main的定义===========
void main()
{
char expression[80],result[80];
cout<<"input the expression:";
cin>>expression;
transform(result,expression);
cout<
//----------------------------------------------------------------
百分之百能运行成功...