栈应用——表达式求值
#include "stdafx.h"
#include <iostream>
using namespace std;
const int EXPLENGHT=20;
const int STACK_INIT_SIZE=20;
const int STACK_INCRMENT=10;
template<typename ElemType>
class Stack
{
public:
Stack()
{
m_base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!m_base)
exit(0);
m_top=m_base;
m_size=STACK_INIT_SIZE;
m_item=0;
}
~Stack()
{
free(m_base);
m_base=m_top=NULL;
}
void push(ElemType e)
{
if(m_top-m_base>=m_size)
{
m_base=(ElemType*)realloc(m_base,(m_size+STACK_INCRMENT)*sizeof(ElemType));
if(!m_base)
exit(0);
m_top=m_base+m_size;
m_size+=STACK_INCRMENT;
}
*(m_top)=e;
m_top++;
m_item++;
}
void pop(ElemType &e)
{
if(m_top==m_base)
return;
m_top--;
e=*m_top;
m_item--;
}
int size()
{
return m_size;
}
bool empty()
{
if(m_item==0)
return true;
else
return false;
}
private:
ElemType *m_base;
ElemType *m_top;
int m_size;
int m_item;
};
void ChangeExp(char *inexp,char *sufexp)//中缀转后缀
{
int i=0;
int j=0;
Stack<char> stack;
while (1)
{
if(inexp[i]=='\0')
{
while(!stack.empty())
stack.pop(sufexp[j++]);
sufexp[j]='\0';
break;
}
char e=inexp[i++];
if(e>='0'&&e<='9')
{
sufexp[j++]=e;
continue;
}
if('*'==e||'/'==e||'('==e)
stack.push(e);
else if(')'==e)
{
char c=' ';
stack.pop(c);
while('('!=c)
{
sufexp[j++]=c;
stack.pop(c);
}
}
else if('+'==e||'-'==e)
{
char c=' ';
while('('!=c&&!stack.empty())
{
stack.pop(c);
if('('!=c)
sufexp[j++]=c;
}
if('('==c)
stack.push(c);
stack.push(e);
}
}
}
int Calculate(char *exp)//计算表达式的值
{
int i=0;
Stack<int> stack;
int num1;
int num2;
while(exp[i]!='\0')
{
if(exp[i]>='0'&&exp[i]<='9')
stack.push(exp[i]-'0');
else
{
stack.pop(num1);
stack.pop(num2);
switch(exp[i])
{
case '+':
stack.push(num2+num1);
break;
case '-':
stack.push(num2-num1);
break;
case '*':
stack.push(num2*num1);
break;
case '/':
stack.push(num2/num1);
break;
}
}
i++;
}
int result;
stack.pop(result);
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
char inexp[EXPLENGHT];
char sufexp[EXPLENGHT];
cout<<"输入中缀表达式(最大长度20):"<<endl;
cin>>inexp;
ChangeExp(inexp,sufexp);
cout<<"后缀表达式:"<<endl;
cout<<sufexp<<endl;
cout<<"运算结果:"<<Calculate(sufexp)<<endl;
system("pause");
return 0;
}

浙公网安备 33010602011771号