//    hhh.cpp  //

#include"hhh.h"

void transform(char *suffix , string s){
 LinkStack S;
 InitStack(S);
 char ch,c;
 push_stack(S,'#');
 istringstream iss(s);
 iss>>ch;int k=0;  //cout<<"iss:"<<ch<<endl;
 while(!stackempty(S)){
  if(!OpMember(ch)) suffix[k++]=ch;//cout<<"suffix:"<<suffix[k-1]<<endl;
  else{
   switch(ch){
    case '(':push_stack(S,ch);break;
    case ')':{
     pop_stack(S,c);
     while(c!='('){
      suffix[k++]=c;//cout<<"suffix:"<<suffix[k-1]<<endl;
      pop_stack(S,c);
     }
     break;
    }
    default:{
     while(gettop(S,c)&&(precede(c,ch))){
      suffix[k++]=c;//cout<<"suffix:"<<suffix[k-1]<<endl;
      pop_stack(S,c);
     }
     if(ch!='#')
      push_stack(S,ch);
     break;
    }//default
   }//switch
  }//else
  if(ch!='#')iss>>ch;  //cout<<"iss:"<<ch<<endl;
 }//while
 suffix[k]='\0';
}

void main()
{
 string s;
 cout<<"请输入合法的表达式,以 # 结束:";
 cin>>s;
 char suffix[100];
 transform(suffix , s);
 int i=0;
 cout<<"相应的后缀表达式为:";
 while(suffix[i]!='\0'){
  cout<<suffix[i];i++;
 }
 cout<<endl<<endl;
}

 

//  hhh.h  //

 

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

 

typedef char 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;//cout<<"pop:"<<e<<endl;
  delete p;
  return true;
 }
 else return false;
}

 

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

 

bool OpMember(char k)
{
 if((k>='A'&&k<='z')||(double(k)-'0'>=1&&double(k)-'0'<=9))
  return false;
 else return true;
}

 

bool stackempty(LinkStack &S)        //判断栈是否为空
{
 if(S==NULL)
  return true;
 else return false;
}

 

char gettop(LinkStack &S, ElemType &e)
{
 if(!stackempty(S)){
  NodeType *p;
  p=new NodeType;
  p=S;
  e=p->data;//cout<<"gettop:"<<e<<endl;
  return e;
 }
 else return 0;
}

 

bool precede(char a, char b)
{
 char x[8]={'#','(','+','-',')','*','/'};
 int y[7]={-1,0,1,1,2,2,2},m,n;
 for(int i=0;i<7;i++){
  if(a==x[i])m=y[i];
  if(b==x[i])n=y[i];
 }
 return m>=n?true:false;
}

 

posted on 2013-04-29 11:17  向云武  阅读(238)  评论(0编辑  收藏  举报