zoukankan      html  css  js  c++  java
  • 栈的表达式求值---通过运算符的优先级比较

    #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;
    }
    
  • 相关阅读:
    通过 WakaTime 统计你写代码的时长
    CCF 202012-3 带配额的文件系统
    1
    prometheus 获取cpu利用率
    springboot使用@data注解,减少不必要代码-lombok插件
    django官方教程部署simpleui时候发现加载不到静态文件解决办法
    echarts关系图研究01
    SpringBoot代码方式禁用Druid Monitor
    virtualbox给已有磁盘扩展容量
    centos7 ssh免密登录配置
  • 原文地址:https://www.cnblogs.com/xyqxyq/p/10211373.html
Copyright © 2011-2022 走看看