表达式求值(栈)

参考课本《数据结构》(C语言版第二版)P77

#include <stdio.h>
#include <stdlib.h>

struct Stack {
	int Top;
	int MaxSize;
	char *ch;
};

struct Stack *CreateStack(int MaxSize);//建立空顺序栈
void Push(struct Stack *&S, char ch);//元素入栈
char GetTop(struct Stack *S);//提取栈顶元素
char Operate(char a, char ch, char b);//a与b的运算
char Precede(char oper1, char oper2);//比较运算符的优先级
int IsChar(char ch);//判断ch是运算符还是数字
char EvaluateExpression();//完成表达式的求值

int main() {
	struct Stack *S;
	S = CreateStack(100);
	printf("%d", EvaluateExpression() - '0' );
	return 0;
}

struct Stack *CreateStack(int MaxSize) {
	struct Stack *S;
	S = (struct Stack *)malloc(sizeof(struct Stack));
	S->ch = (char *)malloc(sizeof(struct Stack) * MaxSize);
	S->MaxSize = MaxSize;
	S->Top = -1;
	return S;
}

void Push(struct Stack *&S, char c) {
	if (S->Top == S->MaxSize - 1)
		return;
	S->ch[++S->Top] = c;
}

char GetTop(struct Stack *S) {
	return S->ch[S->Top] ;
}


char Operate(char a, char ch, char b) {
	if (ch == '+')
		return (a - '0' ) + (b - '0') + '0';
	else if (ch == '-')
		return (a - '0' ) - (b - '0') + '0';
	else if (ch == '*')
		return (a - '0' ) * (b - '0') + '0';
	else if (ch == '/')
		return (a - '0' ) / (b - '0') + '0';
}

char Precede(char oper1, char oper2) {
	if (oper1 == '+' || oper1 == '-') {
		if (oper2 == '+' || oper2 == '-' || oper2 == ')' || oper2 == '#')
			return '>';
		else
			return '<';
	} else if (oper1 == '*' || oper1 == '/') {
		if (oper2 == '(')
			return '<';
		else
			return '>';
	} else if (oper1 == '(') {
		if (oper2 == ')')
			return '=';
		else if (oper2 == '#')
			return false;
		else
			return '<';
	} else if (oper1 == ')') {
		if (oper2 != '(')
			return '>';
		else
			return false;
	} else if (oper1 == '#') {
		if (oper2 == '#')
			return '=';
		else if (oper2 == ')')
			return false;
		else
			return '<';
	}
}

int IsChar(char ch) {
	switch (ch) {
		case '+':
		case '-':
		case '*':
		case '/':
		case '(':
		case ')':
		case '#':
			return true;
			break;
		default :
			return false;
	}
}

char EvaluateExpression() {
	struct Stack *OPND;//存放数字
	struct Stack *OPTR;//存放符号
	OPND = CreateStack(100);
	OPTR = CreateStack(100);
	Push(OPTR, '#');
	char ch;
	scanf("%c", &ch);
	while (ch != '#' || GetTop(OPTR) != '#') {
		if (!IsChar(ch)) {
			Push(OPND, ch);
			scanf("%c", &ch);
		} else
			switch (Precede(GetTop(OPTR), ch)) {
				case '<':
					Push(OPTR, ch);
					scanf("%c", &ch);
					break;
				case '>': {
					char theta = GetTop(OPTR);
					OPTR->Top--;
					char b = GetTop(OPND);
					OPND->Top--;
					char a = GetTop(OPND);
					OPND->Top--;
					Push(OPND, Operate(a, theta, b));
					break;
				}
				case '=':
					OPTR->Top--;
					scanf("%c", &ch);
					break;
			}
	}
	return GetTop(OPND);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值