//   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;
 }
}

posted on 2013-05-03 17:09  向云武  阅读(216)  评论(0编辑  收藏  举报