浙大版《数据结构(第2版)》题目集-习题 3.11

习题3.11 表达式转换 (25point(s))

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。

Example:

#include <iostream>
#include <cstring>

using namespace std;
#define MaxSize  32

void print(char *b, char *e)
{
    static int space = 0;
    if(b == NULL) return ;
    if(space) cout << ' ';
    else space = 1;
    while(b < e) cout << *(b++);
}

int main() 
{
    char str[MaxSize];
    cin >> str;
    char stack[MaxSize];
    int  top = 0;
    char *p = str;
    char *operand = NULL;
    while(1) {
        char ch = *p;
        if(ch == '\0') {
            print(operand, p);
            while(top) cout << ' ' << stack[--top];
            break;
        } else {
            if(strchr("+-*/()", ch)) {
                if(ch == '(') { 
                    stack[top++] = ch;
                } else if(ch == ')') {
                    print(operand, p);
                    operand = NULL;
                    while(top && stack[top-1] != '(') 
                        cout << ' ' << stack[--top];
                    if(top) --top;
                } else if(ch == '*' || ch == '/') {
                    print(operand, p);
                    operand = NULL;
                    while(top && (stack[top-1] == '*' || stack[top-1] == '/'))
                        cout << ' ' << stack[--top];
                    stack[top++] = ch;
                } else if(ch == '+' || ch == '-') {
                    if(p == str || ( strchr("+-*/(", p[-1]) )) {
                        if(operand == NULL) operand = p;
                    } else {
                        print(operand, p);
                        operand = NULL;
                        while(top && (stack[top-1] != '('))
                            cout << ' ' << stack[--top];
                        stack[top++] = ch;
                    }
                }
            } else if(operand == NULL) operand = p;
        }
        p++;
    }
    return 0;
}

思路:

  Partially Accepted。

运算数前有正负号?明明处理了,这表达有点违背直觉,是+123,-456这样子吗?

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值