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;
    }
    
  • 相关阅读:
    数据结构杂谈(三)堆排序
    数据结构杂谈(二)简单有趣的地精排序Gnome sort
    搭建proftp服务器
    python 单例模式
    mongo
    kafka
    查看端口占用
    tinyproxy 代理使用
    Linux 搭建wiki
    linux 安装 java
  • 原文地址:https://www.cnblogs.com/xyqxyq/p/10211373.html
Copyright © 2011-2022 走看看