• 栈的表达式求值---通过运算符的优先级比较


    #include <iostream>
    #include <stdlib.h>
    using namespace std;
    struct SqStack {
    	char *base;
    	char *top;
    };
    int cmp[10][10] = {
    	{'>','>','<','<','<','>','>'},//+
    	{'>','>','<','<','<','>','>'},//-
    	{'>','>','>','>','<','>','>'},//*
    	{'>','>','>','>','<','>','>'},///
    	{'<','<','<','<','<','=',' '},//(
    	{'>','>','>','>',' ','>','>'},//)
    	{'<','<','<','<','<',' ','='},//#
    };
    int in(char c)
    {
    	int ans;
    	switch (c) {
    		case '+':
    			ans = 0;
    			break;
    		case '-':
    			ans = 1;
    			break;
    		case '*':
    			ans = 2;
    			break;
    		case '/':
    			ans = 3;
    			break;
    		case '(':
    			ans = 4;
    			break;
    		case ')':
    			ans = 5;
    			break;
    		case '#':
    			ans = 6;
    			break;
    		default:
    			ans = 7;
    	}
    	return ans;
    }
    char Precede(char a,char b)
    {
    	int v1 = in(a), v2 = in(b);
    	return cmp[v1][v2];
    }
    void InitStack(SqStack &S) {
    	S.base=(char *)malloc(100*sizeof(char));
    	if (!S.base)
    		exit(-1);
    	S.top=S.base;
    }
    char GetTop(SqStack S)
    {
    	return *--S.top;
    }
    void Push(SqStack &S,char e)
    {
    	*S.top++=e;
    }
    void Pop(SqStack &S,char &e) 
    {
    	e=*--S.top;
    }
    char Operate(int a,char t,int b)
    {
    	char ans;
    	switch (t) {
    		case '+':
    			ans = a + b + '0';
    			break;
    		case '-':
    			ans = a - b + '0';
    			break;
    		case '*':
    			ans = a * b + '0';
    			break;
    		case '/':
    			ans = a / b + '0';
    			break;
    		default:
    			ans='0';
    			break;
    	}
    	return ans;
    }
    int main()
    {
        SqStack optr,opnd;
        InitStack(optr);
        InitStack(opnd);
    	Push(optr, '#');
    	char theta, a, b, e;
    	char c = getchar();
    	while (c!='#'||GetTop(optr)!='#') {
    		if (in(c)==7) {
    			Push(opnd, c);
    			c = getchar();
    		}
    		else {
    			e = Precede(GetTop(optr), c);
    			if (e=='<') {
    				Push(optr, c);
    				c = getchar();
    			}
    			else if (e=='=') {
    				Pop(optr, e);
    				c = getchar();
    			}
    			else if (e=='>') {
    				Pop(optr, theta);
    				Pop(opnd, b);
    				Pop(opnd, a);
    				Push(opnd, Operate(a-'0', theta, b-'0'));
    			}
    		}
    	}
    	char ans = GetTop(opnd);
    	cout << ans - '0' << endl;
    	getchar();
    	getchar();
    	return 0;
    }
    
  • 相关阅读:
    ORACLE批量更新四种方法比较
    ra_customer_trx_lines_all 应收发票行
    Toad for Oracle –> Debug by APPS
    应收帐款汇总
    spring3.0.5的rmi集成使用
    java synchronized详解
    用spirng和hessian构建分布式应用(远程接口)的方法(2)
    memcached——分布式内存对象缓存系统
    用spirng和hessian构建分布式应用(远程接口)的方法(1)
    如何在Spring中集成Hessian框架
  • 原文地址:https://www.cnblogs.com/xyqxyq/p/10211373.html
Copyright © 2020-2023  润新知