C++详解 中缀表达式转化为后缀表达式

中缀表达式转化为后缀表达式算法思想细节
首先明确什么是中缀表达式,什么是后缀表达式。
中缀表达式是一个通用的算术或逻辑公式表示方法, 操作符是以中缀形式处于操作数的中间(eg:3+4)。
附:中缀表达式不易被计算机处理。
后缀表达式,又称逆波兰式,指的是不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行(不再考虑运算符的优先规则)。

转化思想:
首先明确中缀转化为后缀过程中,需要转化的部分。
转化内容分为两个部分运算数和运算符号。
运算数:可以分为正数和负数。也可以分为整数和小数。
运算符号:分为六种,包括加减乘除和左右括号。
特别注意:关于数字的处理要注意正负号以及加减的判别。

  1. 括号分为左括号和右括号。左括号直接进栈但不输出,右括号直接开始出栈,直到遇到左括号为止。
  2. 乘除运算在运算转化里处于高级运算的行列。在运算转化过程中,遇到乘除运算直接进栈。
  3. 加减还是正负,This is a question!
    正负的条件:字符串的首字母为正负号。即str[0] = ±;或者正负号的前一个元素为(。eg:(+9),(-9)。处理后应为:9,-9。
    加减的条件:不为正负即为加减。
  4. 数字或小数点直接输出,不影响栈内元素。

代码如下:

#include<iostream>
#include<ctype.h>
#include&l
  • 10
    点赞
  • 83
    收藏
    觉得还不错? 一键收藏
  • 118
    评论
以下是C语言实现中缀表达式转化后缀表达式的代码: ```c #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define MAX_STACK_SIZE 100 typedef struct { char data[MAX_STACK_SIZE]; int top; } Stack; void push(Stack *s, char c) { if (s->top == MAX_STACK_SIZE - 1) { printf("Stack overflow!\n"); exit(EXIT_FAILURE); } s->data[++(s->top)] = c; } char pop(Stack *s) { if (s->top == -1) { printf("Stack underflow!\n"); exit(EXIT_FAILURE); } return s->data[(s->top)--]; } char peek(Stack *s) { if (s->top == -1) { printf("Stack underflow!\n"); exit(EXIT_FAILURE); } return s->data[s->top]; } int is_operator(char c) { return (c == '+' || c == '-' || c == '*' || c == '/'); } int precedence(char c) { if (c == '+' || c == '-') { return 1; } else if (c == '*' || c == '/') { return 2; } else { return 0; } } void infix_to_postfix(char *infix, char *postfix) { Stack s; s.top = -1; int i, j; char c; for (i = 0, j = 0; infix[i] != '\0'; i++) { c = infix[i]; if (isspace(c)) { continue; } if (isdigit(c) || isalpha(c)) { postfix[j++] = c; } else if (is_operator(c)) { while (s.top != -1 && is_operator(peek(&s)) && precedence(c) <= precedence(peek(&s))) { postfix[j++] = pop(&s); } push(&s, c); } else if (c == '(') { push(&s, c); } else if (c == ')') { while (s.top != -1 && peek(&s) != '(') { postfix[j++] = pop(&s); } if (s.top == -1) { printf("Mismatched parentheses!\n"); exit(EXIT_FAILURE); } pop(&s); } else { printf("Invalid character!\n"); exit(EXIT_FAILURE); } } while (s.top != -1) { if (peek(&s) == '(') { printf("Mismatched parentheses!\n"); exit(EXIT_FAILURE); } postfix[j++] = pop(&s); } postfix[j] = '\0'; } int main() { char infix[100], postfix[100]; printf("Enter an infix expression: "); fgets(infix, 100, stdin); infix_to_postfix(infix, postfix); printf("Postfix expression: %s\n", postfix); return 0; } ``` 使用方法: 1. 编译代码:`gcc infix_to_postfix.c -o infix_to_postfix` 2. 运行程序:`./infix_to_postfix` 3. 输入中缀表达式,例如:`(a+b)*c-d/e` 4. 程序输出后缀表达式,例如:`ab+c*de/-`
评论 118
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值