中转转后缀 不知道哪里有问题 求指教

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

输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式:

在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +

/#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
    char a[20] = { 0 };
    char st[20] = { 0 };
    char b[20] = { 0 };
    char ch;
    int coun;
    for (coun = 0; (ch = getchar()) != '\n'; coun++)
    {
        ungetc(ch, stdin);
        scanf("%c", &a[coun]);
    }
    a[coun] = '\0';
    int top = -1, cur1 = 0, cur2 = -1;
    while (a[cur1] != '\0')
    {
        switch (a[cur1])
        {
        case '+':
        case '-':
            while (top >= 0)
            {
                if (st[top] != '(') {
                    cur2++;
                    b[cur2] = st[top];
                    top--;
                }
                else break;
            }
            ++top;
            st[top] = a[cur1];
            cur1++;
            break;
        case '*':
        case '/':
            while (top >= 0) {
                if (st[top] == '*' || st[top] == '/')
                {
                    cur2++;
                    b[cur2] = st[top];
                    top--;
                }
                else
                    break;
            }
            ++top;
            st[top] = a[cur1];
            cur1++;
            break;
        case '(':
            ++top;
            st[top] = a[cur1];
            cur1++;
            break;
        case ')':
            while (st[top] != '(')
            {
                cur2++;
                b[cur2] = st[top];
                top--;
            }
            top--;
            cur1++;
            break;
        default:
            while (a[cur1] >= '1' && a[cur1] <= '9')
            {
                ++cur2;
                b[cur2] = a[cur1];
                cur1++;
            }

        }
    }
    while (top >= 0)
    {
        cur2++;
        b[cur2] = st[top];
        top--;
    }
    printf("%c",b[1]);
    for (int p = 0; p <coun; p++)
    {
        printf(" %c", b[p]);
    }

    return 0;
}

结果如下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值