首页 > 代码库 > 逆波兰表达式

逆波兰表达式

一、 将中缀表达式转换成后缀表达式算法:
1、从左至右扫描 中缀表达式。
2、若读取的是操作数(数字),则判断该操作数的类型,并将该操作数存入操作数堆栈
3、若读取的是运算符
(1) 该运算符为左括号"(",则直接存入运算符堆栈。
(2) 该运算符为右括号")",则输出运算符堆栈中的运算符到操作数堆栈,直到遇到左括号为止。
(3) 该运算符为非括号运算符:
(a) 若运算符堆栈栈顶的运算符为括号,则直接存入运算符堆栈。
(b) 若比运算符堆栈栈顶的运算符优先级高或相等,则直接存入运算符堆栈。
(c) 若比运算符堆栈栈顶的运算符优先级低,则输出栈顶运算符到操作数堆栈,并将当前运算符压入运算符堆栈。
4、当表达式读取完成后运算符堆栈中尚有运算符时,则依序取出运算符到操作数堆栈,直到运算符堆栈为空。
 
二、逆波兰表达式求值算法:
1、循环扫描语法单元的项目。
2、如果扫描的项目是操作数,则将其压入操作数堆栈,并扫描下一个项目。
3、如果扫描的项目是一个二元运算符,则对栈的顶上两个操作数执行该运算。
4、如果扫描的项目是一个一元运算符,则对栈的最顶上操作数执行该运算。
5、将运算结果重新压入堆栈。
6、重复步骤2-5,全部运算完后,最后堆栈中数 即为结果值。
 
链接:逆波兰表达式求值
 
#include<stdio.h>  #include<stdlib.h>  typedef struct stu  {      char s;      struct stu *next;  }stack;  void push(stack **top,char c)  {      stack *p;      p=(stack *)malloc(sizeof(stack));      p->s=c;      p->next=(*top);      *top=p;  }  void pop(stack **top)  {      *top=(*top)->next;  }  int yxj(char a,char b)  {      if((a==+||a==-)&&(b==*||b==\\))          return 0;      return 1;  }  int main()  {      stack *top=NULL;      int m[110];      char s[110],c[110]={0};      int i,j=0,t=1;      gets(s);      for(i=0;s[i]!=@;i++){          if(s[i]>=0&&s[i]<=9){              c[j++]=s[i];              t=0;          }          else{              if(t==0){                  c[j++]= ;                  t=1;              }              if(top==NULL||s[i]==(||(s[i]!=)&&yxj(s[i],top->s)))                  push(&top,s[i]);              else{                  if(s[i]==)){                      while(top->s!=(){                          c[j++]=top->s;                          pop(&top);                      }                      pop(&top);                  }                  else{                      while(top!=NULL&&(!yxj(s[i],top->s))){                          c[j++]=top->s;                          pop(&top);                      }                      push(&top,s[i]);                  }              }          }      }      if(t==0)          c[j++]= ;      while(top!=NULL){          c[j++]=top->s;          pop(&top);      }      c[j]=0;      j=0;      for(i=0;c[i]!=\0;i++){          if(c[i]>=0&&c[i]<=9){              t=0;              for(;c[i]!= ;i++)                  t=t*10+c[i]-48;              m[j++]=t;          }          else{              if(c[i]==+)                  m[j-2]=m[j-2]+m[j-1];              else if(c[i]==-)                  m[j-2]=m[j-2]-m[j-1];              else if(c[i]==*)                  m[j-2]=m[j-2]*m[j-1];              else if(c[i]==/)                  m[j-2]=m[j-2]/m[j-1];              j--;          }      }      printf("%d\n",m[0]);      return 0;  }  
View Code