题目1101:计算表达式 九度OJ

算法:

1.1个栈寄存运算符,1个栈寄存操作数

2.优先级用数组保存好

View Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<string>
#include<math.h>
#include<map>
#include<set>
#include<stack>
#include<algorithm>
using namespace std;
stack<int>OpE;//操作数栈 
stack<char>OpR;//运算符栈 
//算符间优先级 
int Opet[100];
//栈顶优先权 
int Pri[8][8] = {{1,1,-1,-1,-1,1,1},
                 {1,1,-1,-1,-1,1,1},
                 {1,1,1,1,-1,1,1},
                 {1,1,1,1,-1,1,1},
                 {-1,-1,-1,-1,-1,0,0},
                 {1,1,1,1,1,1,1},
                 {-1,-1,-1,-1,-1,-1,-2}
                };
void init( )
{
  memset(Opet,0,sizeof(Opet));
  Opet['+'] = 0,Opet['-'] = 1,Opet['*'] = 2;
  Opet['/'] = 3,Opet['('] = 4, Opet[')'] = 5;
  Opet['#'] = 6;    
}
//判断优先级 
int jugde( char p, char q)
{
   return Pri[Opet[p]][Opet[q]];    
}

int solve(char *str )
{
  int len = strlen(str), x, y, i = 0, j;
  char Op = 0, temp[1100];
  init( );
  OpR.push('#');
  bool f = true;
  str[len] = '#';
  while( i <= len && f)
  {
     if( str[i] >= '0' && str[i] <= '9' ) //操作数直接入栈 
     {  
          int ans = 0;
          for(j = i; j < len; j++)
             if( str[j] >= '0' && str[j] <= '9' )
               temp[ans++] = str[j];
             else
               break;
          i = j;
          temp[ans] = '\0';
          OpE.push(atoi(temp));
     }
     else
     {  
        switch( jugde(OpR.top(),str[i]) )
        {
          case 0: OpR.pop();i++;break; 
          case 1: 
          {
             Op = OpR.top( );
             OpR.pop();
             x = OpE.top();
             OpE.pop();                 
             y = OpE.top( );
             OpE.pop( ); 
             if( Op == '+' )
                 OpE.push( x + y );
             else if( Op == '-' )
                 OpE.push( y - x );
             else if( Op == '*' )
                 OpE.push( y * x );
             else if( Op == '/' )
                 OpE.push( y / x );
             break;    
          }
          case -1: OpR.push(str[i]);i++;break;
          case -2: f = false;break;    
        }    
         
     }    
       
  }     
  return OpE.top();
}
 
int main( )
{
   char str[1000];
   while( scanf("%s",str) != EOF )
   {
     printf("%d\n",solve( str ));
   }
   return 0;
}

转载于:https://www.cnblogs.com/tangcong/archive/2012/08/21/2648464.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值