1. 程式人生 > >棧的表示式求值---通過運算子的優先順序比較

棧的表示式求值---通過運算子的優先順序比較

#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;
}