【数据结构】中缀表达式转后缀表达式

本文介绍了如何使用栈将中缀表达式转换为后缀表达式。详细阐述了处理数字、运算符和括号的策略,包括当遇到操作符时检查栈顶操作符的优先级,遇到右括号时弹出栈顶元素直到匹配的左括号,以及在输入结束时弹出栈内剩余元素。示例中给出了1+2-3*2-1的中缀表达式及其转换后的后缀表达式12+32*-1-。
摘要由CSDN通过智能技术生成

题目描述:
First of all, you are required to complete a Linked stack in stack.cpp.

Linked stack, as the name implies, is a linked structure by using pointer.

Then, we can use this stack to convert infix expression to postfix expression in the MidToLast class.

What is infix expression and postfix expression?

(1) Infix expression: operator is in the middle of the operand, as what you use in your daily life, such ass, 1+2, 3*5-1, 1+2-3*(2-1) and so on.

(2) Postfix expression: contain no bracket, operator is on the back of two operand.

Operation will performe by the order of appearance of operator, strictly from left to right.

For example, 1+2, will be changed to 12+, 3*5-1 will be 35*1-, 1+2-3*2-1 will be 12+32*-1-.

The method to convert the expression is very ingenious and using stack is a good choice.

In this problem, the number is between 0~9, and the symbols are +-*/().

大概的意思就是要你利用栈来实现中缀表达式转后缀表达式。

思路:一个中缀表达式可能包涵数字,运算符,括号。下面的方法就是分几种不同的情况来处理。

1、读到数字时,不放进栈中,直接放到要输出的string里面。

2、读到读到操作符时“+ - * / ”,如果此时栈顶操作符优先性大于或等于此操作符,弹出栈顶操作符放到string里面。直到发现优先级更低的元素或者发现(。

P.S.操作符中,+-优先级最低,()优先级最高。所以要注意的一点是,除非遇到了),不然不弹出(。

3、如果遇到一个右括号,那么就将栈元素弹出,将符号写入string中,直到遇到一个对应的左括号。但是这个左括号只被弹出,并不写入string。

4、如果读到输入的末尾,将栈元素弹出并写入string中,直到该栈变成空栈。

下面是相应的代码:

stack.h:

#ifndef STACK_H
#define STACK_H
#include <iostream>
using namespace std;
struct Node {
  char entry;
  Node *next;
  Node() {
    next = NULL;
  }
  Node(char data, Node *add_on = NULL) {
    entry = data;
    next = add_on;
  }
};
class St
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值