[栈]——中缀转后缀+表达式求值

中缀表达式:普通四则运算

后缀表达式:运算符在数字后面,式子没有括号

中缀变后缀:按照优先级给式子全加上括号,然后把运算符移到对应的括号后面

 

视频

 逆波兰 - 上 中缀表达式 转 后缀表达式

 逆波兰 - 下 后缀表达式计算结果

文章

中缀表达式转后缀表达式 + 后缀表达式的计算

代码

//算术表达式的求值。算术表达式包括以下运算符: ( ) + - * / 。采用堆栈实现。只能是个位数。

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

#define SIZE 50

typedef struct stack {
	char* elem;
	int top;
	int base;
}stack;

void initstack(stack& s) {
	s.elem = (char*)malloc(SIZE);
	if (!s.elem) return;
	s.top = s.base = 0;
}

void push(stack& s, char value) {
	if (s.top == SIZE)  return;
	s.elem[s.top++] = value;
}

char pop(stack& s) {
	if (s.base == s.top) return NULL;
	return s.elem[--s.top];
}

char gettop(stack& s) {
	if (s.base == s.top) return NULL;
	return s.elem[s.top - 1];
}

void show(stack s) {
	for (int i=0;i<s.top;i++) {
		printf("%c", s.elem[i]);
	}
	printf("\n");
}

stack infix_to_suffix(stack& suffix) {
	stack char_stack;
	initstack(char_stack);	
	
	printf("输入算术表达式:");
	char top, temp = getchar();

	while (temp != '\n') {

		if (48 <= temp && temp <= 57)
			push(suffix, temp);

		else if(temp=='(')
			push(char_stack, temp);

		else if (temp == ')'){
			while (gettop(char_stack) != '(')
				push(suffix,pop(char_stack));

			pop(char_stack);
		}
		else {
			top = gettop(char_stack);
			if ((temp == '+' || temp == '-')&&(top == '*' || top == '/')) {			
				while (char_stack.base != char_stack.top)
					push(suffix, pop(char_stack));

				push(char_stack, temp);
			}
			else 
				push(char_stack, temp);
		}
		temp = getchar();
	}
	while (char_stack.top != char_stack.base)
		push(suffix, pop(char_stack));
	printf("后缀式为:");
	show(suffix);
	return suffix;
}

void calc(stack suffix) {
	stack calcs;
	initstack(calcs);
	int pre, post, temp;
	for (int i = suffix.base; i <= suffix.top; i++) {
		temp = suffix.elem[i];
		if (48 <= temp && temp <= 57)
			push(calcs, temp - '0');  //易错点:在计算后缀式时是将每个元素都看成char,各函数都是根据char制定;计算数值时数字不能看成字符,否则会变成ascll码的运算
		else {
			pre = pop(calcs);
			post = pop(calcs);
			switch (temp){
			case '+':push(calcs, post + pre); break;
			case '-':push(calcs, post - pre); break;
			case '*':push(calcs, post * pre); break;
			case '/':push(calcs, post / pre); break;
			}
		}
	}
	printf("结果为:%d", calcs.elem[0]);
}
int main() {
	stack suffix_stack;
	initstack(suffix_stack);
	calc(infix_to_suffix(suffix_stack));
	
}
//9+(3-1)*3+8/2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值