逆波兰

来源:互联网 发布:21天学通c语言 下载 编辑:程序博客网 时间:2024/04/28 15:09

#include<stdio.h>
#include<iostream>
#include<stack>
using namespace std;

int main()
{
 stack<int> s;
 int i=0;
 int flag1,flag2;
 int end=0;
 int tmp;
 char str[40];
 
 while(1)
 {
  
  scanf("%c",&str[i]);
  
  if(str[i]=='\n')
  {
   break;
  }
 
  
  if(str[i]>='0'&&str[i]<='9')
  {
   tmp=int(str[i])-48;
   
   s.push(tmp);
   
  }
  
  if(str[i]=='+')
  {
   flag1=s.top();
   s.pop();
   flag2=s.top();
   s.pop();
   
   tmp=flag1+flag2;
   s.push(tmp);
   
  }
  if(str[i]=='-')
  {
   flag1=s.top();
   s.pop();
   flag2=s.top();
   s.pop();
   
   tmp=flag2-flag1;
   s.push(tmp);
   
  }
   if(str[i]=='/')
  {
   flag1=s.top();
   s.pop();
   flag2=s.top();
   s.pop();
  
   tmp=flag2/flag1;
   s.push(tmp);
   
  }
   if(str[i]=='*')
  {
   flag1=s.top();
   s.pop();
   flag2=s.top();
   s.pop();
   
   tmp=flag1*flag2;
   s.push(tmp);
   
  }
  
  i=i+1;
  
 }
 
 flag1=s.top();
 end=flag1;
 
 printf("%d\n",end);
 return 0;
 
}

原创粉丝点击