后缀表达式求值

//   zzz.cpp   //

#include"zzz.h"

void evaluation(string s)
{
 LinkStack S;
 InitStack(S);
 char ch;
 double a,b;
 istringstream iss(s);
 iss>>ch;
 while(ch!='#')
 {
  if(!OpMember(double(ch))) push_stack(S,(double)ch-'0');
  else
  {
   pop_stack(S,a); pop_stack(S,b);
   push_stack(S,operatorr(b,ch,a));
  }
  iss>>ch;
 }
 pop_stack(S,a);
 cout<<a<<endl;
}

void main()
{
 string s;
 cout<<"请输入合法的后缀表达式,以 # 结束:";
 cin>>s;
 cout<<"表达式的值为:";
 evaluation(s);
}

 

 

//   zzz.h   //

 

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

typedef double ElemType;

typedef struct NodeType{
 ElemType data;
 NodeType *next;
}NodeType,*LinkStack;                  

void InitStack(LinkStack &S)               //初始化栈
{
 S=NULL;
} //InitList


bool pop_stack(LinkStack &S, ElemType &e)        //出栈
{
 NodeType *p;
 p=new NodeType;
 if(S){
  p=S;S=S->next;
  e=p->data;
  delete p;
  return true;
 }
 else return false;
}

void push_stack(LinkStack &S, ElemType e)        //进栈
{
 NodeType *p;
 p=new NodeType;
 p->data=e;
 p->next=S;
 S=p;
}

bool OpMember(double k)
{
 if(k>='1'&&k<='9')
  return false;
 else return true;
}

double operatorr(double b,char ch,double a)
{
 switch(ch)
 {
  case '+':return a+b;break;
  case '-':return b-a;break;
  case '/':return b/a;break;
  case '*':return b*a;break;
  default:break;
 }
}

转载于:https://www.cnblogs.com/yunwux/archive/2013/05/03/3057015.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值